Mobx/Mobx状态是不可观察的!
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>
发布于 2017-05-31 03:09:04
result.state是不可观测的,但是如果您查看其实施情况,就会发现当您执行result.state时,它将访问可观察的result._state。
private _state: IObservableValue<PromiseState> = observable(PENDING as any);
....
get state(): PromiseState {
return this._state.get();
}reaction和when之所以工作是因为它们会对_state访问做出反应,而当您读取state时就会发生这种情况。在文件中清楚地解释了这一点。
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)));https://stackoverflow.com/questions/44170032
复制相似问题