JavaScript: Upgrading from MobX 2.7.0 to 3.0.2
As usual, you should check out the CHANGELOG. However, let me point out a few things specifically:
Don’t use the @action decorator on a singleton object that you pass to observable()
. If you have code that looks like observable({ @action f: () => {})
, you should change it to observable({ f: action(() => {})
. Apparently, using decorators on singleton objects is a little sketchy. I assume the same thing applies to extendObservable. If you’re using classes, it’s a non-issue.
If you have a resolution field in package.json that lists mobx, make sure you keep it in sync with the version of mobx you’re trying to install. Otherwise, you’ll end up with multiple versions of mobx, each with their own state, and that led to ultra-weird behavior for me.
When passing an object to observable()
, remember that it now makes a copy of that object. That was already the case for arrays and maps, but now it’s also the case for normal objects. Hence, when you pass an object into a store, stop using the reference to the old, non-observable object, and instead get a reference to the observable version of that object from the store.
I saw some tests that would create some test object, do something that adds it to the store, and then assume that the original object reference was still valid. For instance:
- The code would use
.toBe
instead of.toEqual
. - The code would assume that if you added something to the original object, it’d be present in the object in the store.
- The code would assume that if you mutated the object in the store, it’d still match the data in the original object.
- The code would assume that you could compare the object in the store with the original object without using
toJS
. You should always usetoJS
when you compare an observable object with a non-observable test object.
Aside from the “easy” stuff mentioned in the changelog, that’s pretty much it.
Published on Web Code Geeks with permission by Shannon Behrens, partner at our WCG program. See the original article here: JavaScript: Upgrading from MobX 2.7.0 to 3.0.2 Opinions expressed by Web Code Geeks contributors are their own. |