2017-05-24 59 views
1

Mobx-utils/fromPromise.state不可觀察!爲什麼與'when'工作和'observe'或'intercept`不一致?

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/[email protected]/lib/mobx.umd.js"></script> 
 
<script src="https://unpkg.com/mobx-utils/mobx-utils.umd.js"></script>

回答

1

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))); 
相關問題