Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Disallow invocation of actions from within computed expressions #830

Closed
winhillsen opened this issue Feb 12, 2017 · 1 comment
Closed

Disallow invocation of actions from within computed expressions #830

winhillsen opened this issue Feb 12, 2017 · 1 comment

Comments

@winhillsen
Copy link

I was playing around with the strict mode behavior and came across the following example.

import { observable, computed, action, useStrict } from 'mobx'; // v3.1.0
useStrict( true );
const value = observable( 100 );
const double = computed( () =>
{
    action( () => value.set( 0 ) )(); // should not be doing this!
    return value.get() * 2;
} );

console.log( double.valueOf() );

What is currently happening is that evaluating double causes its dependency value to be reset to zero right within the evaluation. Strict mode doesn't seem to take offense at this.

IMO in order to guarantee statelessness, computed expressions should be totally side effect-free with respect to the entire mobx state space, and so invoking actions within such expressions should never be allowed.

In case I'm missing something here and the current behavior is in fact intended, it would be good to understand the reasoning behind it. Otherwise it would be great to see an extra safeguard against this (anti-?)pattern, which in some cases can be very hard to spot if the invoked action buries the computed expression deep, deep in the oblivion of the stack trace.

@urugator
Copy link
Collaborator

urugator commented Feb 12, 2017

It was changed quite recently. The side effects are still forbidden, but only if the modified observable is being observed. The reason is basically to allow initializing observable values after they have been defined. For example you call init() action in some constructor (which was required in strict mode because constructor itself can't be an action) and the constructor is called from within some computed.
See #798 for more details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants