vue过程中遇到的Uncaught (in promise) TypeError: Cannot read property '$message' of undefined
vue过程中遇到的Uncaught (in promise) TypeError: Cannot read property '$message' of undefined
在写一个vue项目,想把项目中使用的vue-resource换成vue-axios,语法从http.$http.post变为axios.post,之后,紧接在下面的语句this.$message出现如下报错
![](https://upload-images.jianshu.io/upload_images/21360360-5b39ec97aebe48bc.png?imageMogr2/auto-orient/strip|imageView2/2/w/794/format/webp)
![](https://upload-images.jianshu.io/upload_images/21360360-3f4e4193488bd7f8.png?imageMogr2/auto-orient/strip|imageView2/2/w/825/format/webp)
原来是http.$http.post时this.$message不报错,改成axios.post时this.$message报错,猜想可能是this指向有变化,后查找发现function(response){this.message...}和(res)=>{this.message...}中this的指向是不同的,箭头函数并不简单是匿名函数的简写:
![](https://upload-images.jianshu.io/upload_images/21360360-b02b2ac6cf58b50a.png?imageMogr2/auto-orient/strip|imageView2/2/w/1056/format/webp)
把匿名函数改成箭头函数后成功:
![](https://upload-images.jianshu.io/upload_images/21360360-d3c1342285fa986f.png?imageMogr2/auto-orient/strip|imageView2/2/w/782/format/webp)
转载于:https://www.jianshu.com/p/601762eeadad