Search code examples
javascriptreactjsmobxmobx-react

React + Mobx observer class component doesn't rerender after adding componentDidMount() method


I've found a very strange MobX behavior and I've no idea why it happens. Tried to google it but found nothing about the issue I've faced.

So, I've got a very simple MobX store for the counter:

import { makeAutoObservable } from "mobx";

class CounterStore {
  constructor(initialState) {
    this.count = initialState ?? 0;

    makeAutoObservable(this);
  }

  dec = () => this.count--;

  inc = () => this.count++;

  get color() {
    return this.count > 0 ? "green" : this.count < 0 ? "red" : "black";
  }
}

export default CounterStore;

And the CounterMobx which is React class component:

import { observer } from "mobx-react";
import { Component } from "react";

import CounterStore from "../../stores/CounterStore";

const store = new CounterStore(1);

const CounterMobx = observer(
  class extends Component {
    render() {
      return (
        <div>
          <button onClick={store.dec}>-</button>
          <span style={{ color: store.color }}>{store.count}</span>
          <button onClick={store.inc}>+</button>
        </div>
      );
    }
  }
);

export default CounterMobx;

Everything works just fine until I add componentDidMount() lifecycle method to the CounterMobx component:

componentDidMount() {
  console.log(store);
}

After adding componentDidMount() when I try to change the count value with actions (by clicking "-" or "+" button) nothing happens, component stopped tracking the observable values from store

Is there something I'm doing wrong or this is a bug?

"react": "^18.1.0",
"mobx": "^6.6.0",
"mobx-react": "^7.5.0",

Solution

  • This seems to be a problem with React 18 and <React.StrictMode>. If you remove the <React.StrictMode> component at the top of your component tree for now it should work.