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

react-moment库导入报错:Cannot set properties of undefined (setting 'format')

问题解决:导入react-moment即触发TypeError错误

问题背景

使用pnpm安装了react-moment@1.1.3、moment@2.29.4和moment-timezone@0.5.43,仅执行import Moment from "react-moment"(未使用模块)就出现Uncaught TypeError: Cannot set properties of undefined (setting 'format')错误,导致页面崩溃。

可行解决方案

1. 调整模块导入顺序

react-moment依赖moment模块完成初始化,尝试先导入moment和moment-timezone,再导入react-moment:

import moment from 'moment';
import 'moment-timezone';
import Moment from 'react-moment';

2. 强制统一moment依赖版本

pnpm可能存在多版本moment的依赖冲突,在package.json中添加pnpm覆盖规则,强制所有依赖使用同一版本的moment:

{
  // ... 其他已有配置
  "pnpm": {
    "overrides": {
      "moment": "^2.29.4"
    }
  }
}

执行pnpm install重新安装依赖后再测试。

3. 替换react-moment为自定义组件

react-moment版本较久,可能与React 18或新版moment存在兼容性问题,可直接基于moment封装简易时间组件替代:

import moment from 'moment';
import 'moment-timezone';

const MomentComponent = ({ date, format = 'YYYY-MM-DD HH:mm:ss', timezone }) => {
  const formattedDate = timezone 
    ? moment(date).tz(timezone).format(format)
    : moment(date).format(format);
  return <span>{formattedDate}</span>;
};

export default MomentComponent;

使用时直接导入该自定义组件即可实现react-moment的基础格式化功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 05:58:37