本文分析前端开发中常见的TypeError: Cannot set properties of undefined (setting 'xx')错误,主要原因为axios回调中this指向丢失。提供两种解决方案:使用箭头函数保持上下文,或暂存this变量。结合Vue和Element UI表格数据绑定示例,帮助开发者快速定位并修复此类问题。
TypeError: Cannot set properties of undefined (setting 'xx')
问题描述
在编写使用axios向后端请求数据的代码时,前端页面无法正常渲染,并持续抛出上述错误信息。
报错:
TypeError: Cannot set properties of undefined (setting 'xx')
原因分析:
该错误通常是因为在axios的回调函数中,this的指向发生了改变,此时this不再指向Vue实例,而是指向了axios对象本身。因此,无法通过this访问到Vue实例上的数据属性。解决方法是在调用函数之前,先将当前Vue实例的this引用保存下来。
解决方案:
方法一:在axios的回调函数中使用箭头函数。例如:(response) => {}。箭头函数不会创建自己的this,而是继承外层作用域的this,从而保持对Vue实例的引用。
<template>
<el-table :data="tableData" style="width: 100%" stripe>
<el-table-column prop="name" label="姓名" width="250" />
<el-table-column prop="age" label="年龄" width="250" />
<el-table-column prop="gender" label="性别" width="250" />
<el-table-column prop="createTime" label="创建时间" width="250" />
<el-table-column fixed="right" label="操作" width="250">
<template #default>
<el-button link type="primary" size="small">编辑</el-button>
<el-button link type="primary" size="small">删除</el-button>
</template>
</el-table-column>
</el-table>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
tableData:[]
}
},
created(){//为何 要在created 方法中 发请求,因为该方法 可以操作tableData属性
// 解决方法一
axios.get('http://localhost:9090/student') // url 请求后台的地址
/*
* .then(function (response) 这样写前端会报错
* 报错信息:TypeError: Cannot set properties of undefined (setting 'tableData')at eval (Student.vue?401d:59:1)
* 这样写是匿名函数,无法取到tableData的值,所以tableData的值为undefined,不能给undefined的变量赋值
* 解决办法:1.改为箭头函数 2.将this重新赋值给新的变量
*/
// .then(function (response) { //成功回调方法(访问后台成功,后台有数据返回,则进入该方法)
.then(response=> { //成功回调方法(访问后台成功,后台有数据返回,则进入该方法)
console.log(response);
console.log(response.data)
this.tableData = response.data;
})
.catch(function (error) {//失败回调方法(访问后台失败,返回失败的信息,则进入该方法)
console.log(error);
});
},
methods:{
}
}
</script>方法二:在调用axios前暂存this。定义变量var th = this;,然后在内部回调中使用th.xx来代替this.xx,以访问Vue实例的数据。
//解决办法二
var th = this;
axios.get('http://localhost:9090/student') // url 请求后台的地址
.then(function (response) { //成功回调方法(访问后台成功,后台有数据返回,则进入该方法)
console.log(response);
console.log(response.data)
th.tableData = response.data;
})
.catch(function (error) {//失败回调方法(访问后台失败,返回失败的信息,则进入该方法)
console.log(error);
});到此这篇关于TypeError: Cannot set properties of undefined (setting 'xx')的文章就介绍到这了,更多相关Cannot set properties of undefined内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!