Vue中推送数据失败,报TypeError: Cannot read properties of undefined错误求助
问题分析与解决方案
错误原因
报错Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'push')的核心问题是:你的resources初始是空对象,当后端返回的data.role对应的键在resources中不存在时,this.resources[data.role]的值是undefined,而undefined没有push方法,因此触发了这个错误。
修复方案
在调用push之前,先检查并初始化对应角色的数组:
方案1:显式判断初始化
修改newRole方法中的then回调部分:
.then(response => { Object.values(response.data).forEach(data => { // 先检查当前角色对应的数组是否存在,不存在则初始化空数组 if (!this.resources[data.role]) { this.resources[data.role] = []; } this.resources[data.role].push(data); }); })
方案2:简化初始化逻辑
可以用逻辑运算符简化判断步骤:
.then(response => { Object.values(response.data).forEach(data => { // 若数组不存在则先创建,再执行push (this.resources[data.role] || (this.resources[data.role] = [])).push(data); }); })
额外建议
为了避免后端返回的数据中data.role不存在的情况,可加一层判断,防止出现this.resources[undefined]的无效键:
.then(response => { Object.values(response.data).forEach(data => { if (data?.role) { // 可选链操作符确保role属性存在 if (!this.resources[data.role]) { this.resources[data.role] = []; } this.resources[data.role].push(data); } }); })
修改后的完整代码示例
<script> export default { data(){ return { roleName: null, roleHours: null, resources: {}, } }, methods: { newRole(){ axios.put(`/role/create`, { role: this.roleName, hours: this.roleHours }).then(response => { Object.values(response.data).forEach(data => { if (!this.resources[data.role]) { this.resources[data.role] = []; } this.resources[data.role].push(data); }); } ) }, }, mounted(){ } } </script>
内容的提问来源于stack exchange,提问作者Chibi
相关产品推荐
相关产品推荐

