Javascript Vuex操作-返回Axios承诺

Javascript Vuex操作-返回Axios承诺,javascript,vue.js,vuex,Javascript,Vue.js,Vuex,我在两个地方使用axios返回的承诺时遇到了一些困难。我想在Vuex操作中使用.then()来提交对我的状态的更改,返回axios承诺并在我的组件中再次使用.then()来更新UI。我遇到的问题是,承诺响应在我的组件中没有定义。 如果我在Vuex操作中取消使用.then(),则响应将成为api中的对象,但我希望在组件中有一个承诺,以便捕获错误。 第一个代码块中有什么错误? 谢谢。在第一个块中,您的然后不会返回任何内容:因此它返回未定义的。返回已解决的值可以解决此问题 您必须搜索、MapGet

我在两个地方使用axios返回的承诺时遇到了一些困难。我想在Vuex操作中使用
.then()
来提交对我的状态的更改,返回axios承诺并在我的组件中再次使用
.then()
来更新UI。我遇到的问题是,承诺响应在我的组件中没有定义。

如果我在Vuex操作中取消使用
.then()
,则
响应将成为api中的对象,但我希望在组件中有一个承诺,以便
捕获
错误。

第一个代码块中有什么错误?

谢谢。

在第一个块中,您的
然后
不会返回任何内容:因此它返回
未定义的
。返回已解决的值可以解决此问题

您必须搜索、MapGetter、mapActions并检查异步函数

比如说

如果您请求api,您可以这样做

//api.js

import axios from 'axios'
export aync function getuser() {
  ... 
  ...
  const data = await axios.get(url,{params:{....}})
  return data
}
//component
import {getuser} from '@/app.js'
import {mapAction} from 'vuex'
  data() {
  return {
    data:null
  }
}
methods: {
..mapAction('getUserAction')
  async getUserMethod () {
    this.data = await getuser()
    this.getUserAction(this.data)
  }
}



//store.js
actions: {

getUserAction () {
  // your actions..
  }
}

在第一个块中,您的
then
不返回任何内容(因此返回
未定义的
)@Vivick从第一个
内部返回
数据,然后
工作。非常感谢。欢迎你写一个答案,这样你就可以赢得代表。我现在有另一个问题。链接
.catch(response=>{})
给了我
类型错误:在JSON.stringify中将循环结构转换为JSON
…这将是一个单独的问题,感觉像是axios反序列化中的一个问题
// component
methods: {
  getUser(userId) {
    this.$store.dispatch('GET_USER', userId)
      .then(response => {
        console.log(response); // no longer undefined
      });
  }
}

// vuex
actions: {
  GET_USER: ({commit}, userId) => {
    return api.getUserById(userId); // removed 'then' method
  }
}
//api.js

import axios from 'axios'
export aync function getuser() {
  ... 
  ...
  const data = await axios.get(url,{params:{....}})
  return data
}
//component
import {getuser} from '@/app.js'
import {mapAction} from 'vuex'
  data() {
  return {
    data:null
  }
}
methods: {
..mapAction('getUserAction')
  async getUserMethod () {
    this.data = await getuser()
    this.getUserAction(this.data)
  }
}



//store.js
actions: {

getUserAction () {
  // your actions..
  }
}