mobxjs / mobx-vue

🐉 Vue bindings for MobX
MIT License
475 stars 22 forks source link

How to enable mobx strict mode? #13

Closed ethanyou725 closed 6 years ago

ethanyou725 commented 6 years ago

here is the code, models

import { action, observable, configure } from "mobx";

configure({enforceActions: true}) // strict mode

export default class ViewModel {
  @observable data = [];
  @action.bound load() {
    setTimeout(() => {
      this.data = [{ age: 18, name: 'aaa' }, { age: 19, name: 'bbb' }]
    }, 1500);
  }
}

vue component:

<template>
    <div class="hello">
        <pre>
      {{state.data}}
    </pre>
    </div>
</template>

<script>
import { observer } from "mobx-vue";
import User from '../models/test.js'
export default observer({
  name: 'HelloWorld',
  mounted() {
    this.state.load()
  },
  data() {
    return {
      state: new User()
    }
  }
})
</script>

Uncaught Error: [mobx] Since strict-mode is enabled, chang... The mobx strict mode is useful to prevent some unnecessary problem. I tried add action in vue compoent, it doesn't work, has any way to enable strict model ?

kuitos commented 6 years ago

All reactions in mobx are synchronized, so you need to wrap your async mutation into runInAction method:

setTimeout(() => {
      runInAction(() => this.data = [{ age: 18, name: 'aaa' }, { age: 19, name: 'bbb' }])
    }, 1500);

check the doc: https://mobx.js.org/best/actions.html

ethanyou725 commented 6 years ago

It's my fault, sorry, closed.