vue过程中遇到的Uncaught (in promise) TypeError: Cannot read property ‘$message‘ of undefined

作者:jessi988
链接:https://www.jianshu.com/p/601762eeadad
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在写一个vue项目,想把项目中使用的vue-resource换成vue-axios,语法从http. h t t p . p o s t 变 为 a x i o s . p o s t , 之 后 , 紧 接 在 下 面 的 语 句 t h i s . http.post变为axios.post,之后,紧接在下面的语句this. http.postaxios.postthis.message出现如下报错

vue过程中遇到的Uncaught (in promise) TypeError: Cannot read property ‘$message‘ of undefined

vue过程中遇到的Uncaught (in promise) TypeError: Cannot read property ‘$message‘ of undefined

原来是http. h t t p . p o s t 时 t h i s . http.post时this. http.postthis.message不报错,改成axios.post时this.$message报错,猜想可能是this指向有变化,后查找发现function(response){this.message…}和(res)=>{this.message…}中this的指向是不同的,箭头函数并不简单是匿名函数的简写:

vue过程中遇到的Uncaught (in promise) TypeError: Cannot read property ‘$message‘ of undefined

把匿名函数改成箭头函数后成功:

vue过程中遇到的Uncaught (in promise) TypeError: Cannot read property ‘$message‘ of undefined