You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript项目调用Vuex action报loadItems属性不存在错误如何解决

报错原因及解决方案

1. TS无法识别mapActions注入的方法类型

你当前直接导出普通对象作为组件配置,TS无法自动推导mapActions挂载到this上的方法类型,因此会报找不到loadItems属性的错误。
有两种常用解决方法:

  • 方法一:用defineComponent包裹组件导出
    defineComponent是Vue官方提供的类型推导辅助函数,可以让TS正确识别组件的所有属性类型,修改Index.vue的script部分即可:
<script lang="ts">
import { defineComponent } from 'vue';
import { mapActions } from 'vuex';

export default defineComponent({
    methods: {
        ...mapActions([
            'loadItems'
        ])
    },
    mounted (){
     this.loadItems();
    }
})
</script>
  • 方法二:Vue3项目可直接用组合式API调用store,无需使用mapActions
<script setup lang="ts">
import { useStore } from 'vuex';
import { onMounted } from 'vue';

const store = useStore();
onMounted(() => {
  store.dispatch('loadItems');
})
</script>

2. 修复store代码的笔误

你当前store中mutation定义的名称是SET_Item,但在action调用commit时写的是SET_Items,多了一个s,运行时会触发mutation不存在的报错,需要修改统一:

// store/index.ts的action部分修改commit调用
commit('SET_Item', items)

3. 模块化Vuex补充类型声明(可选)

如果你确实按照模块化拆分了store,还需要给Vuex补充全局类型声明,在shims-vuex.d.ts中添加以下内容即可:

import { Store } from 'vuex'

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $store: Store<{}> // 尖括号内可替换为你项目根State的实际类型
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:27:03