在我的 React 应用程序中,mobx @action 没有触发 - mobx , mobx-react-lite

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

我是第一次使用 mobx & mobx-react-lite,我可以看到 @action 没有触发任何事件。

请找到Code SandBox url here

我的意图是当我点击按钮时,名字 CHAN 应该更改为 XIAN。但它没有发生。你能告诉我我哪里做错了吗?提前致谢。

您在 myStore 构造函数中缺少 makeObservable

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;
  }
}

除了@Christiaan 的回答,您还可以使用 makeAutoObservable 并完全删除装饰器!

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

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

  constructor() {
    makeAutoObservable(this)
  }

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

更多信息:https://mobx.js.org/react-integration.html