You need to enable JavaScript to run this app. Nuxt调用Store Mutation报TypeError: Cannot read property 'setIsDark' of undefined
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt调用Store Mutation报TypeError: Cannot read property 'setIsDark' of undefined

问题根因

报错完全来自对Vuex(Nuxt全局Store底层基于Vuex实现)的调用规则理解偏差:

  • 访问路径错误:Vuex的store实例上没有挂载mutations这个属性,代码执行this.$store.mutations.setIsDark(!this.isDark)时,读取this.$store.mutations得到的就是undefined,自然无法读取其上的setIsDark方法,直接触发类型报错。
  • 调用逻辑错误:Vuex不允许组件内直接调用定义在mutations对象上的方法,要触发对应mutation必须通过store实例暴露的commit方法,传入mutation名称和携带的参数。
修正方案

你在store/index.js里写的全局Store配置本身没有问题,只需要调整组件内的调用逻辑即可:

  • 原有computed中通过getters读取状态的写法完全符合规范,不需要改动,这也是之前你能正常拿到isDark值的原因。
  • 把错误的toggle方法替换为标准写法:
    原错误代码:
    toggleIsDark() {
        this.$store.mutations.setIsDark(!this.isDark);
    }
    
    修正后代码:
    toggleIsDark() {
        this.$store.commit('setIsDark', !this.isDark)
    }
    

调整后即可正常触发状态修改逻辑。

内容的提问来源于stack exchange,提问作者Jackson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.13 13:54:03