【问题标题】:Vuex store cannot be used inside axios handlerVuex store 不能在 axios 处理程序中使用
【发布时间】:2021-03-06 16:40:05
【问题描述】:

我的 Vue 组件中的按钮成功调用了方法:

  methods: {
    goTestMe() {
      console.log(this.$store.state.lang+' 1')
      let url = 'some api url'
      let headers = { headers: { 'Content-Type': 'application/json' } }
      
      this.$axios
        .get(url, headers)
        .then(function(response) {
          console.log('here')
          console.log(this.$store.state.lang+' 2')
        })

问题是这个的输出是:

en-us 1
here

什么时候应该:

en-us 1
here
en-us 2

显然,在 axios 调用的 then() 处理程序中对 this.$store.state 的引用失败了。

这是为什么?如何将我的 axios 请求收到的数据发送到 Vuex 存储?

【问题讨论】:

  • 你尝试过使用异步等待吗?它可能永远不会被调用的原因是该函数完成得太快。因此,axios 请求永远不会得到解决。
  • @FloWy 这不是问题。他使用then 来异步处理promise,这基本上就是async...await 在幕后的意思。约瑟夫在下面的回答是正确的。这个问题是由于this 是对 promise 的执行上下文的引用,比 vue 组件的执行上下文更重要。发生这种情况是因为像这样传递function(){} 表达式会更改上下文。改用() => {} 箭头函数表达式将使this 引用vue 组件上下文。
  • 哦,对不起,我的错:D
  • 谢谢你们。如果您对理解 JS 中的 async/await 和箭头函数有很好的参考,我将不胜感激。

标签: vue.js axios vuex console.log


【解决方案1】:

在普通函数中添加回调时,无法访问全局对象,因此需要将其更改为箭头函数

 methods: {
    goTestMe() {
      console.log(this.$store.state.lang+' 1')
      let url = 'some api url'
      let headers = { headers: { 'Content-Type': 'application/json' } }
      
      this.$axios
        .get(url, headers)
        .then((response) => { // change it to arrow function
          console.log('here')
          console.log(this.$store.state.lang+' 2')
        })
}

【讨论】:

    猜你喜欢
    • 2020-05-10
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 2021-06-17
    相关资源
    最近更新 更多