Mobx 异步示例在操作后不呈现结果

Mobx async example does not render result after action

可以通过codesandbox查看issue

Codesandbox:https://codesandbox.io/s/great-frog-m2s7h

上下文

我正在尝试获取一些数据并填充一些变量并在 React 中呈现值,基本上遵循文档 await/async + runInAction 示例:https://mobx.js.org/actions.html#asynchronous-actions

但是,当获取数据时,React 实际上并没有重新渲染。但是,如果您编辑其中的文本(即将 hi 更改为 his 或其他任何内容,那么您会看到正确的值出现。

问题

我在获取数据时到底做错了什么?为什么在获取某些数据后为可观察值分配了一个值,但未正确重新呈现可观察值?

这是一个简单的错误。 MobX 无法将 title 的数据与不存在的数据进行比较。东西应该有某种默认值,甚至 null。因此在构造函数中,您需要定义 title 默认值,如

constructor() {
    this.title = [],
    makeAutoObservable(this);
}

或者,如果您愿意,甚至 null

constructor() {
    this.title = null,
    makeAutoObservable(this);
}

基本上,每当您在商店中创建一些可观察变量时 - 您需要在 makeAutoObservable.

上方的构造函数中定义其默认值

在这里,您的一个分支项目只需更改这一行即可使其工作https://codesandbox.io/s/suspicious-noether-fnhjw

这实际上是 Mobx 的局限之一。

来自docs

make(Auto)Observable only supports properties that are already defined. Make sure your compiler configuration is correct, or as workaround, that a value is assigned to all properties before using make(Auto)Observable. Without correct configuration, fields that are declared but not initialized (like in class X { y; }) will not be picked up correctly.

只需初始化标题this.title=undefined即可。