Vue error resolution [Vue warn]: Error in render: "TypeError: Cannot read property 'state' of undefined"

Report an error

Error reported in Vue2 project:
[Vue warn]: Error in render: “TypeError: Cannot read property ‘state’ of undefined”
[Vue warn]: Error in mounted hook: “TypeError: Cannot read property ‘dispatch’ of undefined”

Insert image description here

Common causes

This error message usually appears in the Vue component. It tries to read the state object of the Vuex store, but the object is not defined. This may be caused by several reasons:

1. The Vuex store module is not imported correctly. You can import the store using the following code in the Vue component:

import store from '@/store'

This assumes that the store.js file is located in the src/store directory. If the store.js file is located in a different directory, change the import path accordingly.

2. The component is not properly connected to the Vuex store. You can use the following code in a Vue component to connect the component to the Vuex store:

import {
    
     mapState } from 'vuex'

export default {
    
    
  computed: {
    
    
    ...mapState(['myState'])
  }
}

MyState here is the state name defined in the Vuex store. If other names are used in the component, change the code accordingly.

3. The required state is not defined in the Vuex store.
This error will occur if the state you are trying to use is not defined in the Vuex store. The state can be defined in the store.js file using the following code:

const state = {
    
    
  myState: null
}

Solution

After repeatedly confirming the code, I found that there was no such problem. So I wanted to see if it was a version problem. I opened package.json and saw that vuex was version 4.
Insert image description here
That's the solution:
run the following command to uninstall Vuex 4:

npm uninstall vuex

Run the following command to install Vuex 3:

npm install vuex@3

Guess you like

Origin blog.csdn.net/zag666/article/details/130349794