mobx@6.x class 存储无反应

mobx@6.x class store no reactive

当我使用 mobx@6.x 使用 class 类型的商店不反应

示例:

https://codesandbox.io/s/mobx-react-class-store-demo-xzcuv?file=/src/App.tsx

您需要立即初始化您的字段,或者如果您想在构造函数中初始化它们,那么您需要在所有初始化之后调用 makeAutoObservable,否则它不会选择未定义的字段。

class TestStore {
  hello: string;
  // hello = ""; // or just initialize right here with empty string, for example

  constructor() {
    this.hello = "hello world";
    // Call it after all initializations
    makeAutoObservable(this);
  }

  setHello(str: string) {
    console.log("testStore set hello2");
    this.hello = str;
  }
}

更多信息in the docs