React类组件传方法给外部函数组件调用时报this.getproducts不是函数
问题定位与修复方案
触发报错的核心原因
- 类方法this上下文丢失:直接将类方法
this.deleteProduct作为props传递给子组件时,没有给方法绑定指向当前类实例的this。当该方法在子组件的点击事件回调中被独立调用时,内部的this已经脱离原组件实例作用域,自然无法访问实例上定义的getproducts方法,直接抛出"this.xxx is not a function"的类型错误。 - 类方法命名不统一:在类中定义的方法名为
getproducts,但在componentDidMount、deleteProduct内部调用时写的是this.getproductos,名称拼写不匹配,哪怕this绑定完全正常,也会触发方法不存在的报错。 - 子组件props取值层级错误:父组件传递props时是直接赋值
products={products},子组件却写为const { products } = props.product,实际不存在props.product这个嵌套层级,运行时会因为读取undefined的属性抛出额外错误。
具体修复操作
- 解决this绑定问题,两种常用方案任选其一即可:
- 方案一:在类的constructor中手动为需要向外传递的方法绑定当前实例的this:
constructor(props) { super(props); this.state = { products: [], }; // 为deleteProduct绑定指向当前组件实例的this this.deleteProduct = this.deleteProduct.bind(this) } - 方案二:使用类属性箭头函数的形式定义需要向外传递的方法,箭头函数没有自身的this,会自动继承定义时所在作用域的上下文,无需手动绑定:
// 箭头函数写法,自动绑定当前类实例的this async deleteProduct = (id) => { await axios.delete("http://localhost:5000/api/productos/" + id); // 等待删除接口完成后再拉取最新列表,避免出现未处理的Promise异常 await this.getproducts(); }
- 方案一:在类的constructor中手动为需要向外传递的方法绑定当前实例的this:
- 统一所有类方法的命名:将所有调用位置的
this.getproductos全部修改为和方法定义完全一致的this.getproducts,消除拼写不匹配问题。 - 修正子组件的props取值逻辑:去掉错误的嵌套层级,直接从props顶层解构需要的属性:
export default function ListTemplate(props) { // 父组件直接在props顶层传products和delBtn,不存在props.product层级 const { products, delBtn } = props; return ( <div className="container"> <div className="header"> <h2>Product List:</h2> </div> {products?.map((product) => ( <div className="body" key={product._id}> <span>{product.name}</span> <span>{product.model}</span> <span>${product.price}</span> <button type="button" className="btn btn-danger btn-sm" onClick={() => delBtn(product._id)} > Delete Item </button> </div> ))} </div> ) }
修复后运行逻辑
完成上述调整后:
- 组件挂载时会正常调用
getproducts拉取商品列表 - 点击删除按钮触发
delBtn回调时,deleteProduct内部可以正常访问组件实例的上下文,完成删除请求后重新拉取最新商品列表,更新state并重新渲染页面
内容的提问来源于stack exchange,提问作者Axel Bentancur
相关产品推荐
相关产品推荐

