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>
答案 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();
}
reaction
和when
有效,因为他们会对_state
访问做出反应,当您阅读state
时会发生这种情况。这清楚地解释了in the documentation。
observe
和intercept
不起作用,因为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)));