调试vue程序,使用axios请求后台报错,源码如下:

getGoodsList () {
       axios.get('/v1/random')
         .then(function (response) {
           this.article = 'sss'
           console.log(response.title)
           console.log(response)
         })
         .catch(function (error) {
           console.log(error)
         })
    }
  },

报错为:TypeError: Cannot set property ‘article’ of undefined vue
axios请求后article 发生变化,而我使用的是名字函数,this 关键字是匿名函数,vue实例,改成箭头函数就行,如下:

getGoodsList () {
      // axios.get('/v1/random')
      //   .then(function (response) {
      //     this.article = 'sss'
      //     console.log(response.title)
      //     console.log(response)
      //   })
      //   .catch(function (error) {
      //     console.log(error)
      //   })
      axios.get('/v1/random').then((response) => {
        this.article = 'sss'
      })
    }

参考链接:https://stackoverflow.com/questions/43613115/vue-cannot-set-property-of-undefined-in-promise
https://www.cnblogs.com/stella1024/p/7598541.html

Logo

前往低代码交流专区

更多推荐