我正在学习 MobX,不明白为什么 autorun
只触发一次...
const {observable, autorun} = mobx;
class FilterStore {
@observable filters = {};
@observable items = [1,2,3];
}
const store = window.store = new FilterStore;
setInterval(() => {
store.items[0] = +new Date
}, 1000)
autorun(() => {
console.log(store.filters);
console.log(store.items);
console.log('----------------');
});
jsFiddle: https://jsfiddle.net/1vmtzn27/
这是一个非常简单的设置,setInterval
每秒都会更改我的可观察数组的值,但是 autorun
不会被触发...知道为什么吗?
最佳答案
...and the
setInterval
is changing the value of my observable array every second...
不,不是。它正在改变数组的内容,但不是可观察的 MobX 正在观察,它是 store.items
本身。改变那个会像这样:
store.items = [+new Date];
由于您没有在 autorun
回调中访问 store.items[0]
,因此不会监视更改。 (console.log
确实访问了它,但不是以 MobX 可以看到的方式。)
如果您确实访问了store.items[0]
,它会被监视变化;如果您向数组添加或从数组中删除,您可能还想显式访问 length
:
autorun(() => {
store.filters;
store.items.length;
store.items.forEach(function() { } );
console.log('Update received');
});
关于javascript - MobX 自动运行只触发一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41087194/