Mobx: Observing a store property seems to work when using Typescript but not when using ES6/Babel

Created on 1 Jun 2016  ·  8Comments  ·  Source: mobxjs/mobx

Running the following snippet with ES6/Babel leads to an invariant error:

class Store {
  @observable foo = ''
}

const store = new Store();

mobx.observe(store, 'foo', () => {
  console.log('Change observed');
}, true);

// --> Invariant failed: first argument of observe should be an (observable)object or observableMap if a property name is given

Running it with Typescript (tried in JSBin) seems to work just fine.

🐛 bug

All 8 comments

Might be related to #285 as well. Seems like something weird is going on with class instances that is inconsistent between TypeScript and ES6.

@AriaFallah Right, looks like there is something fishy here.

argh always babel. will take a look tomorrow.

Op wo 1 jun. 2016 17:44 schreef Luc Heinrich [email protected]:

@AriaFallah https://github.com/AriaFallah Right, looks like there is
something fishy here.


You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
https://github.com/mobxjs/mobx/issues/288#issuecomment-223035036, or mute
the thread
https://github.com/notifications/unsubscribe/ABvGhDdsmQw-YOhEf9T_ClXTHAdSzd3Fks5qHajhgaJpZM4IrjZT
.

_Update_: the mobx version that I was using in JSBin was old (2.0.3), so I did the test again with the latest version (2.2.2). The problem remains the same (works when using TS but not Babel) but the error message is different:

Error: [mobx] Invariant failed: Cannot obtain atom from [object Object]

FWIW

Could you share the JSBin?

Note for those following this issue, the workaround for this problem is to access the observed property _before_ observing it because properties are made reactive lazily, as explained here: https://github.com/mobxjs/mobx/blob/master/test/babel/babel-tests.js#L90

In that case, a simple console.log(store.foo) (for example) before the call to observe makes it work.

Thanks for the reproduction! The cause is in the lazy initialization of the properties (only on first use), until a patch is available the following work around fixes this issue:

const store = new Store();
store.foo; // kicks of property initialization

observe(store, 'foo', ...
Was this page helpful?
0 / 5 - 0 ratings