Skip to content

Disallow invocation of actions from within computed expressions #830

@winhillsen

Description

@winhillsen

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions