React+TS运行报Unhandled Rejection: props.prices不是函数如何解决
错误原因与修复方案
核心报错根因
你遇到的Unhandled Rejection (TypeError): props.prices is not a function报错,本质原因是:
你在Prices组件的Props接口中定义了prices是一个接收ICrypto类型参数的回调函数,但你在父组件中调用Prices组件时,没有传入这个prices属性,导致props.prices默认值为undefined,尝试调用它的时候自然会抛出「不是函数」的类型错误。
除此之外你的代码还有2处逻辑问题需要同步修复,否则即使解决了当前报错,也拿不到正确的价格数据:
- 你直接把接口请求写在组件函数体中,组件每次渲染都会重复发起请求
- 接口请求成功后没有读取返回的价格数据,反而直接调用回调传了空的
pricesState
分步修复方案
1. 调用Prices组件时传入必填的prices回调
在父组件使用Prices组件的位置,按照接口定义传入回调函数,示例如下:
// 父组件代码示例 import Prices from './prices/Prices'; const ParentComponent = () => { return ( <div> {/* 传入prices回调,定义拿到价格后要执行的逻辑 */} <Prices prices={(cryptoPrices) => { // 示例:打印拿到的加密货币价格,你可以替换成自己的业务逻辑,比如存到父组件状态 console.log('BTC价格:', cryptoPrices.BTCUSD); console.log('ETH价格:', cryptoPrices.ETHUSD); }} /> </div> ) }
2. 修复Prices组件的接口请求逻辑
将接口请求放到useEffect钩子中,避免重复调用,同时读取接口返回的价格数据:
// 首先导入useEffect钩子 import React, { useState, useEffect } from 'react'; import { backendAPIAxios } from '../../../utils/http'; import { ICrypto } from '../../../models/crypto'; import PricesView from './Prices.view'; interface Props { readonly prices: (value: ICrypto) => void; } const Prices: React.FC<Props> = (props: React.PropsWithChildren<Props>) => { const [ pricesState, setPricesState ] = useState<ICrypto | null>(null); const pricesChangeHandler = (value: ICrypto | null) => setPricesState(() => value); // 把接口请求放在useEffect中,组件挂载时仅执行一次 useEffect(() => { backendAPIAxios.get<ICrypto>(`/prices`) .then((res) => { // 读取接口返回的价格数据 const cryptoPrices = res.data; // 更新当前组件状态 setPricesState(cryptoPrices); // 调用父组件传入的回调 props.prices(cryptoPrices); }); }, [props.prices]); return ( <PricesView prices={pricesState} pricesChangeHandler={pricesChangeHandler} >{props.children}</PricesView> ); }; Prices.displayName = 'Prices'; Prices.defaultProps = {}; export default Prices;
3. 可选优化:将prices设为可选属性
如果这个回调不是必须传入的,可以修改Props定义为可选,调用前做非空判断,避免遗漏传参时报错:
// 修改Props定义,加问号标记为可选 interface Props { readonly prices?: (value: ICrypto) => void; } // 调用时加可选链判断,不存在就不执行 props.prices?.(cryptoPrices);
内容的提问来源于stack exchange,提问作者user16657995
相关产品推荐
相关产品推荐

