为什么 reaction 对 `when` 有效,而对 `observe` 或 `intercept` 无效?

Why reaction with `when` works and with `observe` or `intercept` not?

Mobx-utils/fromPromise.状态不可观察!

const { observable, when, reaction, intercept, observe, isObservable } = mobx;
const { fromPromise, whenWithTimeout } = mobxUtils;

const promise = fetch('https://jsonplaceholder.typicode.com/todos')
  .then(res => res.json())
const result = fromPromise(promise);

console.assert(isObservable(result.state), 'state is NOT an isObservable');

/* WORKS!
when(
  () => result.state !== "pending",
  () => {
    console.log("Got ", result.value)
  }
);
*/

// NOT WORK, Why ?
observe(result, 'state', change => (console.log('observe', change)), true)
intercept(result, 'state', change => (console.log('intercept', change)));
reaction(
  () => result.state,
  state => console.log('reaction', state)
);
<script src="https://unpkg.com/mobx@3/lib/mobx.umd.js"></script>
<script src="https://unpkg.com/mobx-utils/mobx-utils.umd.js"></script>

result.state 是不可观察的,但是如果你看一下 its implementation 你会发现当你做 result.state 它访问可观察的 result._state.

private _state: IObservableValue<PromiseState> = observable(PENDING as any);
....
get state(): PromiseState {
    return this._state.get();
}

reactionwhen 起作用是因为它们对 _state 访问作出反应,当您阅读 state 时会发生访问。这个解释的很清楚in the documentation.

observeintercept 不起作用,因为 result 不可观察。他们希望他们的 第一个 参数是 可观察的 。因此,即使更新后的代码也无法正常工作

observe(result, '_state', change => (console.log('observe', change)), true)
intercept(result, '_state', change => (console.log('intercept', change)));

要修复它,请将 result._state 作为第一个参数。

observe(result._state, change => (console.log('observe', change)), true)
intercept(result._state, change => (console.log('intercept', change)));