mobx@6.x 类存储无反应

问题描述

当我使用 mobx@6.x 与类类型存储不反应

示例:

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