【问题标题】:Vue Axios - not sure why I can't call a function on this responseVue Axios - 不知道为什么我不能在这个响应上调用函数
【发布时间】:2020-05-08 22:44:47
【问题描述】:

我正在更新以前开发人员的代码,但我一直在纠结为什么我不能这样做,因为代码返回了这个错误:

Uncaught (in promise) TypeError: failedCallback is not a function

这是我正在使用的函数:

export default {
  get(callback, failedCallback) {
    axios.get(`/admin/shops`)
         .then(response => callback(response.data))
         .catch(errors => failedCallback(errors))
  }
}

然后像这样导入:

import getShop from '../api/shops'

并在我的全局路由器保护中这样使用

router.beforeEach((to, from, next) => {
  if(to.name == null){
    getShop.get(
      data => {
        if(data.setup) {
          debugger;
          this.$store.dispatch('getBackground', false); #this is the line that causes the error!
          next({ name: 'customers_table'});
        }
        else {
          next({ name: 'plans'})
        }
      });
  }
  else {
    next();
  }
})

当我添加下面的行时,我得到了 TypeError

this.$store.dispatch('getBackground', false);

不知道为什么会出现该错误或如何解决?

编辑: 这是我的getBackground 操作

getBackground: ({ commit }, payload) => {
  commit('changeBackground', payload);
}

【问题讨论】:

  • 你能把错误信息也贴出来吗?
  • @helper 是的,它在顶部.. 这就是错误
  • 您能发布 getBackground 操作的代码吗? (这就是引发异常的原因)
  • @helper 确定.. 我将它添加到 OP

标签: vue.js axios


【解决方案1】:

你的回调抛出了被 catch 块捕获的错误。 catch 块正在尝试调用您未提供给getShop 的failedCallback。这就是为什么它会引发 failedCallback 的类型错误。

Uncaught (in promise) TypeError: failedCallback is not a function

错误的最初原因是this.$store。 this在路由器中无法使用商店。

您需要像这样在路由器文件中导入商店。

import store from '<whereever store is defined>'

store.dispatch('getBackground', false);

或者像这样导入 Vue 并从 protptype 访问 store。

import Vue from 'vue'

Vue.prototype.$store.dispatch('getBackground', false);

【讨论】:

    【解决方案2】:

    您定义了一个 get 函数,该函数在参数中接受两个函数,但您将一个函数传递给它,错误表明失败回调不是函数:

    并考虑到您不在组件内,因此 this.$store 不起作用。 如果您像下面这样导出商店: store.js

    export const store = new Vuex.Store({
    //everything is inside
    })
    

    你应该使用:

    import {store} from './store'
    

    或者如果您使用导出默认值,那么您应该使用:

    import store from './store'
    

    然后像下面这样使用:

    store.getters.isAuthenticated

    正如 linusburg 在本主题中所解释的: https://forum.vuejs.org/t/how-to-use-vuex-in-router/13520

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 2015-01-04
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      相关资源
      最近更新 更多