首页 > 解决方案 > mobx@6.x 类存储无反应

问题描述

当我将 mobx@6.x 与类类型存储一起使用时,不要反应

例子:

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

标签: reactjsmobxmobx-react

解决方案


您需要立即初始化您的字段,或者如果您想在构造函数中初始化它们,那么您需要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;
  }
}

文档中的更多信息


推荐阅读