In my React application, mobx @action is not firing - mobx , mobx-react-lite

1.2k views Asked by At

I am using mobx & mobx-react-lite for first time and I can see the @action is not firing any events.

Please find the Code SandBox url here

My intention is when I click on button, the name CHAN should change to XIAN. But it's not happening. Can you please let me know where I made wrong? Thanks in advance.

2

There are 2 answers

3
Chris On BEST ANSWER

You are missing the makeObservable in the myStore constructor.

Codesandbox

Documentation

import { observable, action, makeObservable } from "mobx";

export class myStore {
  @observable name: string = "CHAN";

  constructor() {
    makeObservable(this)
  }

  @action
  setName(newName: string) {
    this.name = newName;
  }
}
3
Danila On

In addition to @Christiaan answer, you can also use makeAutoObservable and drop decorators altogether!

import { observable, action, makeAutoObservable } from "mobx";

export class myStore {
  name: string = "CHAN";

  constructor() {
    makeAutoObservable(this)
  }

  setName(newName: string) {
    this.name = newName;
  }
}

More info: https://mobx.js.org/react-integration.html