【问题标题】:Vuex Action - Returning Axios PromiseVuex Action - 返回 Axios Promise
【发布时间】:2019-05-08 00:40:21
【问题描述】:

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

// component
methods: {
  getUser(userId) {
    this.$store.dispatch('GET_USER', userId)
      .then(response => {
        console.log(response); // undefined
      });
  }
}

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

// api service
getUserById(userId) {
  return axios.get('/api/users/' + userId);
}

如果我在我的 Vuex 操作中删除 .then() 的使用,response 将成为我的 api 中的对象,但我想在我的组件中有一个承诺,以便我可以 catch 错误。

// 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
  }
}

第一个代码块有什么问题?
谢谢。

【问题讨论】:

  • 在第一个块中,您的 then 不返回任何内容(因此返回 undefined
  • @Vivick 从第一个 then 内部返回 data 有效。谢谢你。欢迎您写一个答案,这样您就可以获得代表。

标签: javascript vue.js vuex


【解决方案1】:

在第一个块中,您的 then 不返回任何内容:因此它返回 undefined。返回已解决的值应该可以解决此问题。

【讨论】:

  • 我现在有另一个问题。链接.catch(response => {}) 给了我TypeError: Converting circular structure to JSON at JSON.stringify...
  • 这将是一个单独的问题,感觉像是 axios 反序列化的问题
【解决方案2】:

你必须搜索、mapGetters、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..
  }
}

【讨论】:

    猜你喜欢
    • 2019-09-23
    • 2019-02-13
    • 2021-09-10
    • 2016-12-27
    • 2018-11-26
    • 2021-07-23
    • 2019-07-30
    • 2021-12-11
    相关资源
    最近更新 更多