简体   繁体   中英

vuex error - do not mutate vuex store state outside mutation handlers

I need help.

I am using Quasar 2 (Vue 3 framework).

Why does state.authorization = data.data.data.authorization; in mutation returns "[vuex] do not mutate vuex store state outside mutation handlers" error?

Store

import { reactive } from 'vue'
import axios from 'axios'
import { SessionStorage } from 'quasar'

import { LOGIN } from './actions'
import AuthService from './service'

const state = reactive({
  authorization: SessionStorage.getItem('authorization') || null
});

const getters = {
  getAuthorization: state => state.authorization
};

const actions = {
  // Login
  [LOGIN]: ({ commit }, data) => {
    return AuthService.login(data).then(
      data => {
        commit(LOGIN, { data: data });
        return Promise.resolve(data);
      },
      error => {
        commit(LOGIN_ERROR);
        return Promise.reject(error);
      }
    );
  }
}

const mutations = {
  // Login
  [LOGIN]: (state, data) => {
    SessionStorage.set('authorization', data.data.data.authorization);
    state.authorization = data.data.data.authorization;
    axios.defaults.headers.common['Authorization'] = 'Bearer ' + data.data.data.authorization;
  }
}

export default {
  state,
  getters,
  actions,
  mutations
};

Within.vue file

let data = {
  email: email.value,
  password: password.value
};

store.dispatch(LOGIN, data).then(...

Thank you!

Changing

const state = {
  authorization: SessionStorage.getItem('authorization') || null
};

to

const state = () => ({
  authorization: SessionStorage.getItem('authorization') || null
});

fixed the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM