Search code examples
reactjstypescriptstatemobx-reactreact-state

MobX console.log() works but render() method doesn't update using React.Component


MobX updates the store emitted by console.log() but does not actually update render() method of React.Component. What am I missing in this example?

@observer
export class App extends Component {
  constructor(props) {
    super(props);
    this.onClick = this.onClick.bind(this);
  }

  @observable data = {
    error: ""
  };

  onClick() {
    this.data.error = "error has occurred";
    console.log(this.data.error) // testing purposes
  }

  render() {
    return (
      <div>
        <div className="red">[ {this.data.error} ]</div>
        <input type="button" value="Click Me!" onClick={this.onClick} />
      </div>
    );
  }
}

CodeSandbox

Credit: Original code from Stackoverflow


Solution

  • In MobX v6, calling makeObservable(this) within the constructor method is required to make class decorators work.

    See these docs for more info.

    See this sandbox for a working example.