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

React项目出现Cannot read properties of undefined(reading 'toString')错误

问题解决:TypeError: Cannot read properties of undefined (reading 'toString')

问题原因

你没直接调用toString,但Ant Design的Statistic组件内部会对传入的value执行toString做格式化处理。当globalStats的某个属性(比如totalExchanges、totalMarketCap等)为undefined时,传给Statistic的value就会是undefined,组件内部处理时就会触发这个错误。

虽然你用了isFetching判断加载状态,但存在请求完成后data?.data?.stats依然为undefined的情况,这时渲染Row里的Statistic组件就会报错。

解决方案

有两种可行的修复方式:

1. 给Statistic的value设置默认值

给每个可能为undefined的属性添加默认值,避免传入undefined给Statistic:

<Row>
  <Col span={12}>
    <Statistic title='Total Cryptocurrencies' value={globalStats?.total || 0} />
  </Col>
  <Col span={12}>
    <Statistic title='Total Exchanges' value={millify(globalStats?.totalExchanges || 0)} />
  </Col>
  <Col span={12}>
    <Statistic title='Total Market Cap' value={millify(globalStats?.totalMarketCap || 0)} />
  </Col>
  <Col span={12}>
    <Statistic title='Total 24h Volume' value={millify(globalStats?.total24hVolume || 0)} />
  </Col>
  <Col span={12}>
    <Statistic title='Total Markets' value={millify(globalStats?.totalMarkets || 0)} />
  </Col>
</Row>

2. 条件渲染Row组件

确保globalStats存在后再渲染Row,避免数据未就绪时渲染统计组件:

{globalStats && (
  <Row>
    <Col span={12}>
      <Statistic title='Total Cryptocurrencies' value={globalStats.total} />
    </Col>
    <Col span={12}>
      <Statistic title='Total Exchanges' value={millify(globalStats.totalExchanges)} />
    </Col>
    <Col span={12}>
      <Statistic title='Total Market Cap' value={millify(globalStats.totalMarketCap)} />
    </Col>
    <Col span={12}>
      <Statistic title='Total 24h Volume' value={millify(globalStats.total24hVolume)} />
    </Col>
    <Col span={12}>
      <Statistic title='Total Markets' value={millify(globalStats.totalMarkets)} />
    </Col>
  </Row>
)}

内容的提问来源于stack exchange,提问作者amirhossein

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 10:54:37