组件调用store的action返回undefined,无法使用其返回值是什么原因?
问题根因
你的 initialize action 函数本身没有显式返回值,代码中 return true 和 return false 是 .then/.catch 回调函数的返回值,仅作用于回调内部,不会作为外层 action 函数的返回值,因此 action 执行后默认返回 undefined。
解决方案
方案1:直接返回Promise结果
在axios调用前添加return,将then/catch处理后的Promise结果作为action的返回值:
export const actions = { async initialize ({ state, commit, dispatch }) { return await this.$axios.get('myEndpoint') .then((res) => { return true }).catch((error) => { return false }) } }
方案2:使用try/catch写法(更推荐)
async/await语法可以搭配try/catch实现更清晰的异步逻辑,不需要混用then/catch回调:
export const actions = { async initialize ({ state, commit, dispatch }) { try { await this.$axios.get('myEndpoint') return true } catch (error) { return false } } }
补充说明
如果你的组件没有通过mapActions将store的initialize action映射为组件方法,需要手动调用dispatch触发action:
async mounted () { const initializeResult = await this.$store.dispatch('initialize') console.log(initializeResult) }
内容的提问来源于stack exchange,提问作者drake035
相关产品推荐
相关产品推荐

