Angular 5报错TypeError: Cannot read property {functionName} of undefined求助
解决Angular 5中Papa Parse调用组件方法时的
Cannot read property 'csvToJSON' of undefined错误 这个问题我太熟悉了!你碰到的这个报错,核心原因是函数内部的this指向不对,咱们来一步步搞定它:
错误原因分析
你在step配置里用了普通的function (row) {...}回调函数,这个函数里的this并不会指向你的Angular组件实例,而是指向Papa Parse的内部上下文。所以当你尝试调用this.csvToJSON时,自然找不到这个方法,就会抛出“无法读取未定义的属性‘csvToJSON’”的错误。
三种可行的解决方案
方案1:使用箭头函数(最推荐,Angular项目常用写法)
箭头函数不会创建自己的this,它会继承外层作用域的this(也就是你的组件实例)。把step的回调换成箭头函数就行:
onSubmit() { this.papa.parse(this.csvFile, { step: (row) => { // 替换为箭头函数 const jsonObj = this.csvToJSON(row.data[0]); console.log(jsonObj); } }); }
方案2:提前保存组件的this到变量
在调用parse之前,先把组件的this存到一个变量里(比如that),然后在回调函数里用这个变量来调用方法:
onSubmit() { const that = this; // 保存组件实例的this this.papa.parse(this.csvFile, { step: function (row) { const jsonObj = that.csvToJSON(row.data[0]); // 用that代替this console.log(jsonObj); } }); }
方案3:用bind绑定this
把回调函数和组件的this绑定在一起,强制让函数内部的this指向组件实例:
onSubmit() { this.papa.parse(this.csvFile, { step: function (row) { const jsonObj = this.csvToJSON(row.data[0]); console.log(jsonObj); }.bind(this) // 绑定组件的this到回调函数 }); }
额外验证点
确保你的csvToJSON函数是定义在组件类中的实例方法(没有加static关键字),这样组件实例才能正常访问到它。
内容的提问来源于stack exchange,提问作者Bilalwcheema
相关产品推荐
相关产品推荐

