【发布时间】:2019-08-17 12:59:32
【问题描述】:
我从 Mobx 收到了这条警告信息。
[mobx.array] 尝试读取超出范围 (0) 的数组索引 (0)。请先检查长度。 MobX 不会跟踪超出范围的索引
@observable checks = {
deviceType: ['phone','laptop', ...],
deviceTypeChecks: [],
...
}
@action
selectAllChecks = (target, type) => {
const targetChecks = []
if (this.checks[target].length !== this.checks[type].length) {
this.checks[target].forEach(el => targetChecks.push(el))
}
this.checks[type] = targetChecks
}
如何删除该警告?但是,这段代码没有问题。效果很好。
我正在通过 onChange 函数使用selectAllChecks 函数。
const {
deviceType,
deviceTypeChecks
} = this.props.store.checks
<label className="mr10">
<input
type="checkbox"
checked={deviceType.length === deviceTypeChecks.length}
onChange={() =>
selectAllChecks('deviceType', 'deviceTypeChecks')
}
/>
<span>All device type</span>
</label>
IE 需要 4 个版本。
"mobx": "^4.1.0",
"mobx-react": "^5.2.6",
还有其他解决办法吗?
【问题讨论】:
-
在比较长度之前是否应该检查
this.checks[target].length > 0?看起来您在 observable 确认新数据之前正在读取索引,因为如果比较的数组没有收集任何项目,上面显示的长度比较总是会返回 true。我对MST比较熟悉,直接mobx-react用的不多。 -
我试着检查
this.checks[target].length如你所说。但警告仍在发生。谢谢 -
你能说明这个函数的使用方式/位置吗?
-
请检查上面的编辑代码。我正在通过 onChange 事件使用该功能。
-
它与
checksobj 无关,因为它不是数组。检查代码中哪里有一个可观察的数组。
标签: reactjs mobx mobx-react