You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React子组件传函数报错:Uncaught (in promise) TypeError: result is not a function

解决子组件调用父组件传递的props函数时报错"result is not a function"

常见原因及修复方案

1. Props名称不匹配

子组件期望接收名为result的函数props,但父组件可能传递时写错了名称(比如直接传了logFunction={logFunction}而非result={logFunction})。

父组件修复示例:

import ChildComponent from './ChildComponent';

function ParentComponent() {
  const logFunction = (data) => {
    console.log('API返回数据:', data);
  };

  // 确保props名称与子组件期望的一致
  return <ChildComponent result={logFunction} />;
}

2. 类组件中函数未绑定this

如果父组件是类组件,类方法默认不会绑定this,直接传递会导致方法丢失上下文,变成非函数值。

类组件修复示例:

import React, { Component } from 'react';
import ChildComponent from './ChildComponent';

class ParentComponent extends Component {
  // 用箭头函数自动绑定this
  logFunction = (data) => {
    console.log('API返回数据:', data);
  };

  render() {
    return <ChildComponent result={this.logFunction} />;
  }
}

或者在构造函数中手动绑定:

constructor(props) {
  super(props);
  this.logFunction = this.logFunction.bind(this);
}

logFunction(data) {
  console.log('API返回数据:', data);
}

3. 子组件未正确接收props

子组件可能存在解构错误,或者未正确从props中获取result函数。

子组件修复示例:

import React, { useEffect } from 'react';
import axios from 'axios';

function ChildComponent({ result }) { // 正确解构result
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('https://your-api-endpoint.com');
        // 调用前先校验类型,避免报错
        if (typeof result === 'function') {
          result(response.data);
        }
      } catch (err) {
        console.error('API请求失败:', err);
      }
    };

    fetchData();
  }, [result]); // 将result加入依赖数组

  return <div>子组件内容</div>;
}

export default ChildComponent;

4. 父组件传递的不是函数

检查父组件中logFunction是否被误定义为非函数值(比如const logFunction = "test"),这种情况下传递给子组件的是字符串/其他类型,自然无法作为函数调用。

额外优化建议

在子组件调用result前增加类型校验,能有效避免因props传递错误导致的运行时报错,提升代码健壮性。

内容的提问来源于stack exchange,提问作者Miguel Angel Marroquin Jordan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 15:40:38