为什么与`when`的反应和`observe`或`intercept`没有反应?

时间:2017-05-24 23:28:34

标签: mobx

Mobx-utils / fromPromise.state是不可观察的!

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>

1 个答案:

答案 0 :(得分:2)

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)));