0

How can I write this with mobx and axios? I am trying to use the arrow function to keep the scope of "this" but I might be doing it wrong.

@action saveMode() {

    axios.post('/Course/Post', { Name: "test41515"})
        .then(response => {
            console.log(response, this.isEditing);
            this.isEditing = !this.isEditing;
            this.failedValidation = [];
        })

}

Uncaught (in promise) Error: [mobx] Invariant failed: Since strict-mode is enabled, changing observed observable values outside actions is not allowed. Please wrap the code in an `action` if this change is intended. Tried to modify: Course@5.isEditing
    at invariant (app.bundle.js:7316)
    at fail (app.bundle.js:7311)
    at checkIfStateModificationsAreAllowed (app.bundle.js:7880)
    at ObservableValue.prepareNewValue (app.bundle.js:5786)
    at setPropertyValue (app.bundle.js:6663)
    at Course.set [as isEditing] (app.bundle.js:6631)
    at app.bundle.js:62336
    at <anonymous>
chobo2
  • 75,304
  • 170
  • 472
  • 780

1 Answers1

0

MobX has a whole page in their documentation about writing async actions. That would be the place to start, https://mobx.js.org/best/actions.html, and in fact the first example is exactly the issue you're facing with the note

The above example would throw exceptions, as the callbacks passed to the fethGithubProjectsSomehow promise are not part of the fetchProjects action, as actions only apply to the current stack.

Given your snippet, the easiest fix is to use runInAction

@action saveMode() {

  axios.post('/Course/Post', { Name: "test41515"})
    .then(response => {
      runInAction(() => {
        console.log(response, this.isEditing);
        this.isEditing = !this.isEditing;
        this.failedValidation = [];
      });
    })

}
loganfsmyth
  • 135,356
  • 25
  • 296
  • 231