uni-app中this.$store为undefined的主因是未在main.js中挂载Store实例,常见错误包括未执行Vue.use(Vuex)、store导出非Vuex.Store实例、main.js未传入store选项、路径别名配置错误等。

uni-app 里 Vuex 不是开箱即用的,必须手动创建 Store 实例并挂载到 Vue 实例,否则 this.$store 会是 undefined。
为什么 this.$store 总是 undefined
常见错误是只建了 store/index.js,但没在 main.js 中传入 store 选项。uni-app 内置 Vuex(Vue 2 项目对应 vuex@3.6.2),但不会自动初始化或挂载。
- 漏掉
Vue.use(Vuex)—— 尤其在模块化写法中容易忽略 -
store/index.js导出的是普通对象(如export default { state: {} }),而非new Vuex.Store({})实例 -
main.js中new Vue({ render: h => h(App) })没加store字段 - 路径写错,比如
import store from '@/store'却没配@别名,导致导入失败
store/index.js 必须这么写
不能省略构造函数调用,也不能用 ES Module 默认导出一个配置对象。最小可用结构如下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
token: uni.getStorageSync('token') || ''
},
mutations: {
SET_TOKEN(state, token) {
state.token = token
uni.setStorageSync('token', token)
}
},
getters: {
isLoggedIn: state => !!state.token
}
})
-
state初始化时建议从uni.getStorageSync读取,保证冷启动时状态一致 - 如果要用模块(
modules),每个模块文件(如modules/user.js)必须export default一个含state(不能是函数)、mutations等字段的对象 - 不要在
state里放不可序列化的值(如函数、Date、RegExp),否则 H5 端可能报错
在组件里正确使用 mapState / mapMutations
不能直接修改 this.$store.state.xxx,必须通过 mutations;读取也推荐用 mapState 或 mapGetters,而不是反复写 this.$store.state。
立即学习“前端免费学习笔记(深入)”;
-
mapState必须放在computed里,例如:...mapState(['token'])或...mapState('user', ['name'])(模块命名空间) -
mapMutations要放在methods里,例如:...mapMutations(['SET_TOKEN']),然后在事件中调用this.SET_TOKEN(newToken) - 跨页面读写时,注意小程序端
onShow/onHide生命周期不会自动触发响应式更新,需主动调用this.$forceUpdate()或依赖watch监听getters
模块化后命名空间容易踩坑
启用 namespaced: true 后,所有 mapState/mapActions 都要显式声明模块名,否则找不到。
- 模块定义里必须写
namespaced: true,否则mapState('user', [...])无效 -
actions中调用其他模块的mutation,得用commit('user/SET_NAME', ...),不能省略前缀 - 调试时看 Vue Devtools 的
Store面板,若模块没展开、状态为空,大概率是namespaced和映射写法不匹配
最常被忽略的一点:Vuex 状态在 App 端 nvue 页面中可用,但仅限于由 vue 页面跳转而来;如果是独立 nvue 页面(如首页设为 nvue),this.$store 仍存在,但部分生命周期钩子(如 onLoad)触发时机与 vue 页面不同,需额外判断状态是否已就绪。


















