从原型调用时,unshift & splice 不适用于可观察数组

unshift & splice don't work for observable arrays when calling from prototypes

考虑以下使用 MobX 5.15.4 的示例:

class Store {
  @observable.shallow items = [];
}

const store = new Store();
store.items = [5, 6, 7, 8, 9];
Array.prototype.push.apply(store.items, [10, 11, 12, 13, 14]);
Array.prototype.unshift.apply(store.items, [0, 1, 2, 3, 4]);

为可观察数组调用 Array.prototype.unshift 对我不起作用(而 Array.prototype.push 有效)。这是堆栈跟踪:

mobx.module.js:3390 Uncaught Error: [mobx.array] Index out of bounds, 14 is larger than 10
    at Array.set (mobx.module.js:3390)
    at Object.set (mobx.module.js:3058)
    at Proxy.unshift (<anonymous>)
    at Module../index.js (index.js:30)
    at __webpack_require__ (bootstrap:89)
    at Object.0 (index.js:6200)
    at __webpack_require__ (bootstrap:89)
    at checkDeferredModules (bootstrap:45)
    at Array.webpackJsonpCallback [as push] (bootstrap:32)
    at index.js:1

Array.prototype.splice 也不行:

Array.prototype.splice.apply(store.items, [0, 0].concat([0, 1, 2, 3, 4]));

这是一个错误还是我误解了什么?我想我应该使用可观察数组的原型来使其工作。我尝试了以下但仍然没有运气:

const observableArrayPrototype = store.items.__proto__;
observableArrayPrototype.unshift.apply(store.items, [0, 1, 2, 3, 4]);

getPrototypeOf 有效

let items = mobx.observable([]);

items = items.concat([5, 6, 7, 8, 9]);
console.log(items);

items.push.apply(items, [10, 11, 12, 13, 14]);
console.log(items);

items.unshift.apply(items, [0, 1, 2, 3, 4]);
console.log(items);


let items1 = mobx.observable([]);
const observablePrototype = Object.getPrototypeOf(items1);

items1 = items1.concat([5, 6, 7, 8, 9]);
console.log(items1);

observablePrototype.push.apply(items1, [10, 11, 12, 13, 14]);
console.log(items1);

observablePrototype.unshift.apply(items1, [0, 1, 2, 3, 4]);
console.log(items1);
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mobx/5.15.4/mobx.umd.js"></script>

你会使用展开运算符吗?你一定可以打电话

store.items.push([10, 11, 12, 13, 14]);

完成。如果您有 newItems 数组,请使用

store.items.push(...newItems);

否则,你需要一个循环。