Nuxt调用Vuex store的action时报unknown action type错误怎么解决?
问题排查与修复方案
- 核心错误1:Vuex模块属性写法错误
Vuex规范中仅state需要定义为返回对象的函数,避免多实例引用污染,actions、getters、mutations均需要直接导出普通对象。你当前将actions和getters包裹为返回对象的函数,导致Vuex无法正常注册对应的方法,触发未知类型错误。 - 核心错误2:导入与拼写错误
mapActions是Vuex的命名导出项,导入时需要加花括号,你之前的写法import mapActions from 'vuex'会导入undefined,无法正常映射方法- 部分调用代码中action名多写了末尾的
s,定义的是fetchArtikel,调用时写成fetchArtikels,名称不匹配也会触发报错
修复后的代码
store/artikels.js
export const state = () => ({ artikel: [ { id: "1", titel: "Hallo", untertitel: "Servas" }, { id: "2", titel: "Was", untertitel: "Wos" }, { id: "3", titel: "Geht", untertitel: "Wüst" } ] }) // 直接导出对象,不要包裹一层函数 export const actions = { fetchArtikel() { console.log('fetch data from firebase') } } // 直接导出对象,不要包裹一层函数 export const getters = { artikel: (state) => { return state.artikel } }
index.vue 两种调用方式任选其一即可
方式1:直接通过$store调用
<script> export default { name: 'App', computed: { artikel() { return this.$store.state.artikels.artikel } }, async created() { // 注意名称和定义完全一致 await this.$store.dispatch('artikels/fetchArtikel') } } </script>
方式2:通过mapActions映射调用
<script> // 导入时加花括号 import { mapActions } from 'vuex' export default { name: 'App', computed: { artikel() { return this.$store.state.artikels.artikel } }, methods: { // 命名空间模块映射第一个参数传模块名,第二个传方法名数组 ...mapActions('artikels', ['fetchArtikel']) }, async created() { await this.fetchArtikel() } } </script>
内容的提问来源于stack exchange,提问作者suavoo
相关产品推荐
相关产品推荐

