无法转存axios响应?Vue中characters数组提示属性未定义报错
报错核心原因
你遇到的Cannot read property 'characters' of undefined报错,根源是普通函数定义的axios回调没有正确绑定Vue组件实例的this指向:
在then和catch里使用function关键字定义回调时,函数内部的this值由实际调用的执行上下文决定,并不会自动指向当前的Vue组件实例。这时候你写的this.characters,因为this本身不存在于回调执行的上下文里(值为undefined),自然触发了属性读取失败的报错。
具体修复方案
方案1:使用箭头函数作为回调(推荐写法)
箭头函数没有自身的this绑定,会直接继承外层created钩子作用域的this,也就是指向当前Vue组件实例,完全适配现代前端开发的环境要求。修正后的代码如下:<script> const axios = require("axios"); export default { data: () => ({ characters:[], }), created() { axios .get("https://rickandmortyapi.com/api/character") // 替换普通function为箭头函数 .then((response) => { const resp = response.data.results; this.characters.push(...resp); }) .catch((error) => { console.log(error); }); }, }; </script>方案2:提前缓存组件实例的this(兼容旧环境写法)
如果需要兼容不支持箭头函数的老旧运行环境,可以在发起axios请求前,把当前组件实例的this存为局部变量,在回调里通过这个变量访问data中定义的数组:<script> const axios = require("axios"); export default { data: () => ({ characters:[], }), created() { // 提前缓存当前组件实例 const vm = this; axios .get("https://rickandmortyapi.com/api/character") .then(function(response) { const resp = response.data.results; // 使用缓存的vm变量访问数组 vm.characters.push(...resp); }) .catch(function(error) { console.log(error); }); }, }; </script>
额外避坑提示
原代码中直接写this.characters.push(resp)会存在结构异常问题:resp本身就是接口返回的角色列表数组,直接push会把整个数组作为单个元素塞入characters,最终得到嵌套的二维数组。使用展开运算符...把数组元素逐个推入,才能得到预期的一维角色列表结构。
内容的提问来源于stack exchange,提问作者Sebastian Jimenez
相关产品推荐
相关产品推荐

