ReactJS Mobx 项目没有更新

问题描述

我正在尝试使用 MobX 构建一个扫雷游戏,我遇到的问题是我不明白为什么我在板上的单元格不会更新。

这是一个包含我的代码的沙箱

https://codesandbox.io/s/epic-sun-n1dnz?file=/src/Components/CellComponent.js

在我的“CellComponent”中我定义了:

            <Button onClick={() => game.unveilCell(cell)}>{revealed? "2" : "?"}</Button>

所以我希望当我点击单元格时,它会显示数字 2 但只有当我等待大约 1 分钟它更新时,我假设我使用的 MobX 观察者是错误

after waiting 1 minute

解决方法

您需要使 makeAutoObservable 调用成为 Cell 构造函数中的最后一个:

export default class Cell {
  value;
  x;
  y;
  revealed;
  flag;

  constructor(x,y) {
    this.x = x;
    this.y = y;
    this.revealed = false;
    this.flag = false;
    this.value = 0;
    // It should be in the end,after all initialisations
    makeAutoObservable(this);
  }

  // ...

默认情况下,没有额外配置 MobX 不能拾取未定义的字段并使它们可观察。