React调用async函数报错:this.createIndicator is not a function
解决
TypeError: this.createIndicator is not a function 问题 这个错误的核心原因是**addNewIndicator函数的this上下文丢失**——当它作为props传给子组件并被调用时,this并没有指向你的React组件实例,自然找不到createIndicator方法。下面是几种快速修复的方案:
方案1:把addNewIndicator改成箭头函数
箭头函数会自动绑定当前组件实例的this,这是最简洁的解决方式:
addNewIndicator = (attrs = {}) => { const value = attrs.value || 'Indicator' const type = attrs.type || 'Generic Type' // 注意:这里then要传一个函数,不然console.log会立即执行 this.createIndicator(value).then( () => console.log('Indicator Created.') ) }
方案2:在constructor中手动绑定this
如果习惯用普通函数定义方法,可以在组件的构造函数里手动绑定addNewIndicator的this:
constructor(props) { super(props); // 绑定this到组件实例 this.addNewIndicator = this.addNewIndicator.bind(this); } // 保持原有的普通函数定义 addNewIndicator(attrs = {}) { const value = attrs.value || 'Indicator' const type = attrs.type || 'Generic Type' this.createIndicator(value).then( () => console.log('Indicator Created.') ) }
方案3:传递props时用箭头函数包裹
如果你不想修改addNewIndicator的定义,也可以在父组件传递这个方法给子组件时,用箭头函数包裹,确保this指向正确:
// 父组件传递props给子组件时 <ChildComponent addNewIndicator={(attrs) => this.addNewIndicator(attrs)} />
额外的小提醒
你的代码里还有一个容易忽略的小问题:then(console.log('Indicator Created.'))会在调用this.createIndicator的同时立即执行console.log,而不是等到Promise完成后执行。正确的写法应该是把console.log放在一个箭头函数里,就像上面方案里写的那样。
内容的提问来源于stack exchange,提问作者Magicked
相关产品推荐
相关产品推荐

