Observability with properties of function type errors?
I'm working on a wrapper for async data that'll keep track of the pending/loaded states of the external data. This is much like what's recommended in the mobx docs for async operations.
However, when I tried to add some simple helper functions to access the state, I get some weird errors. Is this a bug in mobx, intended but not documented behavior, or did I just miss it?
Consider the following code:
'use strict';
const mobx = require('mobx');
let testState = mobx.observable({
state: 'pending',
isPending: function() { return true; },
isLoaded: function() { return false; }
});
console.log('isPending = ', testState.isPending());
When I run this, I get:
> node index.js
D:\Dev\mobx_test\index.js:11
console.log('isPending = ', testState.isPending());
^
TypeError: testState.isPending is not a function
at Object.<anonymous> (D:\Dev\mobx_test\index.js:11:39)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.runMain (module.js:575:10)
at run (node.js:348:7)
at startup (node.js:140:9)
at node.js:463:3
dev:\mobx_test
>
If I remove the mobx.observable call it of course runs just fine.
If I run something substantially similar in karma, I get:
true is not a constructor (evaluating 'store.isPending()')
Any ideas what's going on here?
I don't want to put these methods on the prototypes, because these objects don't need a prototype otherwise.
I have a workaround, but I'd love to understand what's going on here.
observable and extendObservable automatically convert argumentless functions into computed properties. That is clearly not what you intend here, so you should either mark these methods as actions or assign them after passing the object through observable
let testState = mobx.observable({
state: 'pending',
isPending: action(function() { return true; }),
isLoaded: action(function() { return false; })
});
// or
let testState = mobx.observable({
state: 'pending',
})
testState. isPending = function() { return true; };
Ahh, thanks, that makes sense.
Actually, I could easily use the properties instead here, as long as I know what's happening. Thanks for the help!