Search code examples
javascriptvue.jselectronvuexelectron-vue

Vuex Electron: Exception when committing mutation


I am writing an Electron app using Vue and Vuex.

My store is as follows (counter.js):

const state = {
  main: 5
};

const mutations = { // synchronous tasks
  INCREMENT_MAIN_COUNTER (state) {
    state.main++;
  }
};

const getters = {
  count: (state) => {
    return state.main;
  }
};

export default {
  state, getters, mutations
}

My Vue component is as follows (LandingPage.vue):

<template>
  <div id="count-box">
    {{count}}
    <button @click="pressed">Increment counter</button>
  </div>
</template>

<script>
  import counter from '../store';

  export default {
    name: 'landing-page',
    computed: {
      count: () => {
        return counter.getters.count;
      }
    },
    methods: {
      pressed: () => {
        counter.commit('INCREMENT_MAIN_COUNTER');
      }
    }
  };
</script>

When I click the button to increment, the commit is called, and the following exception is triggered:

Uncaught Error: [Vuex Electron] Please, don't use direct commit's, use dispatch instead of this.
    at Store.store.commit (.../node_modules/vuex-electron/dist/shared-mutations.js:1)
    at VueComponent.pressed (LandingPage.vue?b116:20)
    at invoker (vue.esm.js?a026:2027)
    at HTMLButtonElement.fn._withTask.fn._withTask (vue.esm.js?a026:1826)

I don't understand exactly what could be causing this, as I have been following https://www.youtube.com/watch?v=LW9yIR4GoVU and https://vuex.vuejs.org/guide/mutations.html which appear to be doing it this way.


Solution

  • Please note that you're probably using vuex-electron in order to share your vuex store between all processes (including main).

    The project's README.md is clear about that :

    In renderer process to call actions you need to use dispatch or mapActions. Don't use commit because actions fired via commit will not be shared between processes.

    I suppose the reason behind this is Vuex Electron uses ipcMain and ipcRenderer under the hood to communicate between main and renderer processes and both APIs are asynchronous. The point here is mutations must be pure functions and do not have side-effects whereas actions do.

    I get the same error while updating my existing code base to use the latest version of electron-vue which now uses Vuex Electron. Depending on your needs, you can remove Vuex Electron if you don't need to share your store with other processes or add "proxy" actions that call mutations.

    More details in the vuex documentation: