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

React JS中Intl.NumberFormat报错.format is not a function求助

解决.format is not a function报错问题

问题核心原因

你遇到的报错本质是导出与导入方式不匹配:

  • currency.js中使用的是命名导出(export let currencyFormatter)
  • 但page.jsx里用了默认导入(import currencyFormatter from ...)

这种不匹配会导致currencyFormatter实际是一个包含目标变量的对象,而非Intl.NumberFormat的实例,调用.format方法自然会报错。

两种修复方案

方案一:修改导入方式(推荐,保留命名导出)

将page.jsx中的导入代码改为命名导入,用花括号包裹变量名:

import { currencyFormatter } from "../../../utility/currency";

方案二:修改导出方式为默认导出

如果想保留默认导入的写法,修改currency.js的导出代码:

export default new Intl.NumberFormat("en-GB", {
  style: "currency",
  currency: "GBP",
  minimumFractionDigits: 2,
});

额外验证点

修复导入导出问题后,建议确认item.price是数字类型。如果它是字符串格式,需要先转换为数字再调用格式化方法:

currencyFormatter.format(Number(item.price))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 04:30:03