MobX console.log() 有效,但 render() 方法不会使用 React.Component 更新

MobX console.log() works but render() method doesn't update using React.Component

MobX 更新了 console.log() 发出的存储,但实际上并没有更新 React.Componentrender() 方法。我在这个例子中遗漏了什么?

@observer
export class App extends Component {
  constructor(props) {
    super(props);
    this.onClick = this.onClick.bind(this);
  }

  @observable data = {
    error: ""
  };

  onClick() {
    this.data.error = "error has occurred";
    console.log(this.data.error) // testing purposes
  }

  render() {
    return (
      <div>
        <div className="red">[ {this.data.error} ]</div>
        <input type="button" value="Click Me!" onClick={this.onClick} />
      </div>
    );
  }
}

CodeSandbox

来源:来自

的原始代码

在 MobX v6 中,需要在 constructor 方法中调用 makeObservable(this) 才能使 class 装饰器工作。

有关详细信息,请参阅 these docs

有关工作示例,请参阅 this sandbox