MobX自动运行行为 [英] MobX autorun behavior

查看:145
本文介绍了MobX自动运行行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在探索MobX并对一个问题感兴趣:

I'm exploring MobX and went intrigued by a problem:

如果我有这个观察结果:

If I have this observable:

class ItemsStore {
    @observable items = [1,2,3];
}
const store = new ItemsStore;

然后像这样更改:

setInterval(() => {
    store.items[0] = +new Date
}, 1000)

我注意到以下情况:

  • autorun(() => console.log(store.items)); never fires...
  • autorun(() => console.log(store.items[0])); fires every 1s and gives a new value
  • autorun(() => console.log(store.items.length)); fires every 1s although value is unchanged

这背后的API逻辑是什么?我希望由于 store.items 永远不会触发,未更改的属性的行为会相同。

What is the API logic behind this? I would expect that since store.items never fires, that unchanged properties would behave the same.

为什么MobX知道我的回调中有什么代码?它是否正在分析我的回调我传递给 autorun

And how come MobX knows what code is inside my callback? is it analysing my callback I pass to autorun?

推荐答案

console.log(store.items)

当上次自动运行中取消引用的可观察对象发生更改时,将触发自动运行。 store.items 不会取消引用任何可观察对象。尝试 store.items.slice() store.items.toJS()以获得所需的效果。

An autorun is fired when the observables that were dereferenced in the last autorun are changed. store.items does not dereference any observables. Try store.items.slice() or store.items.toJS() to get the desired effect.

console.log(store.items [0])

这是因为已取消引用的可观察值已更改。

This fired because the observable that got dereferenced is changed.

console.log(store.items.length)

这是因为MobX阵列不是真正的阵列而运行。 length 属性是 定义如下

This is run because a MobX array is not a real array. The length property is defined as follows:

Object.defineProperty(ObservableArray.prototype, "length", {
    enumerable: false,
    configurable: true,
    get: function(): number {
        return this.$mobx.getArrayLength();
    },
    set: function(newLength: number) {
        this.$mobx.setArrayLength(newLength);
    }
});

getArrayLength 报告已观察到MobX阵列

getArrayLength(): number {
    this.atom.reportObserved();
    return this.values.length;
}

这篇关于MobX自动运行行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆