LoginSignup
24
16

More than 3 years have passed since last update.

Vue.js:Vuexのエラー:「[vuex] Do not mutate vuex store state outside mutation handlers」の原因と対応例

Last updated at Posted at 2019-08-28

原因

  • コンポーネントの「v-model」に、stateの値を設定していたため。
  • v-modelは参照と設定を同時に行うため、タイトルのエラーが発生する。
issue.vue

<template>
 <!-- v-modelにstateの値を設定 ->
 <v-test-comp v-model="theValue"></v-test-comp>
</template>

<script>
import { mapState } from "vuex";

export default {
  computed: {
    //stateの値にアクセスできるよう設定
    ...mapState(["theValue"])
  }
}
</script>

対応

  • v-modelに設定する値を算出プロパティに置き換える。
  • 算出プロパティのgetでstateの値を返却し、set内で、storeのactionを呼び出す。
resolve.vue

<template>
 <!-- v-modelにstateの値を設定 ->
 <v-test-comp v-model="theValue"></v-test-comp>
</template>

<script>
import { mapState } from "vuex";

export default {
  computed: {
    theValue: {
      get() {
        return this.$store.theValue
      },
      set(value) {
        this.$store.dispatch("setTheValue", value)
      }
    }
  }
}
</script>

24
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
16