Looks like observers of arrays don't fire if you dereference e.g., index 0 on an empty array, then add items to the array. Not sure if the cause of this falls into the same bucket as "object properties that don't exist yet", but having observers not fire if an array starts out empty sounds like a great way to get very subtle bugs.
const observable = require("mobx").observable;
const autorun = require("mobx").autorun;
const o = observable({val: []});
autorun(() => console.log(o.val[0])); // prints undefined
o.val.unshift(new Date().toLocaleString()); // nothing printed
The problem is that mobx ObservableArray is simply a javascript object with numbered keys, so it can't know that you have used some key that don't exist (at least, in es5 environment). Mobx predefines getters and setters for indexes 0-999, that can be used to peak dependency. It could be easily implemented, see #382. but I'm affraid, the fact that first 1000 indexes works differently, than another will lead to inconsistency. @mweststrate, what do you think?
@spiffytech, For now have 2 options:
const o = observable({val: new Array(1)});autorun(() => console.log(o.val.slice()[0]))@andykog I think it will indeed cause weird inconsistencies if certain array indexes are not automatically observed anymore (this 1000 number could be safely increased a lot, but still). But I think it is safe to print a warning when accessing an entry outside the length range. @spiffytech That would probably help as well and avoid confusion?
Note that checking the length in the autorun also yields the correct behavior: autorun(() => console.log(o.val.length ? o.val[0] : "")
Explicitly added this case to the docs now. Hope that helps in the future!
https://github.com/mobxjs/mobx/blob/gh-pages/docs/best/react.md#incorrect-access-out-of-bounds-indices-in-tracked-function
Just released 2.3.5, which will print a warning when detecting an access of out-of-bound index entries
The stack trace can be short not mentioning erroneous code in question.
Maybe proxy access to arrays that when if index is out of bounds with reduce() returning undefined while still printing the warning, after which if array is populated just turn back to original behavior?
Most helpful comment
Just released 2.3.5, which will print a warning when detecting an access of out-of-bound index entries