trace() 错误 "can only be used inside a tracked computed value or a Reaction" 在计算内部使用时

trace() error "can only be used inside a tracked computed value or a Reaction" when used inside computed

我已经使用 MobX 几年了,并且喜欢它,但有时我的跟踪调用不起作用,我不明白为什么。一定有一些基本的东西我完全误解了,但很可能已经很幸运地通过了。这是一个使用 trace() 的示例,但我遇到了错误:

import { computed, observable, trace } from "mobx";

class Stat {
  @observable baseValue = 1;

  @computed get value() {
    trace();

    return this.baseValue;
  }
}

const strength = new Stat();

strength.baseValue = strength.baseValue + 1;

在我看来,预期的输出是跟踪对“baseValue”的变化做出反应并记录变化。相反,我收到以下错误:

Error: [MobX] 'trace(break?)' can only be used inside a tracked computed value or a Reaction. Consider passing in the computed value or reaction explicitly

据我所知,“在跟踪的计算值中”正是我正在做的事情。或者..?

完整沙盒:https://codesandbox.io/s/mobx-trace-trouble-ki2qj?file=/index.ts:0-312

据我了解这句话

inside a tracked computed value or a Reaction.

您需要在反应上下文中访问计算值,例如在 observerreactionautorun 中。否则 trace 只是没有关于正在发生的事情的信息,因为你的计算值在那一刻没有被任何观察者跟踪。

所以这会起作用:

const MyComponent = observer(() => {
    return <div>{strength.value}</name>
})

或这个

autorun(() => {
  console.log(strength.value);
});