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

React项目使用chartjs-adapter-date-fns遇‘time未注册’错误求助

解决Chart.js中"time"未注册的Scale错误

在React项目中使用react-chartjs-2的Bubble图表,配置X轴为time类型时,控制台反复抛出以下错误,组件无法渲染:

Uncaught Error: "time" is not a registered scale.

移除options.scales.x.type = "time"配置后,X轴显示毫秒时间戳,图表可正常渲染。原代码如下:

原导入代码

import {
  Chart as ChartJS,
  LinearScale,
  PointElement,
  Tooltip,
  Legend,
} from "chart.js";
import "chartjs-adapter-date-fns";
import { Bubble } from "react-chartjs-2";

ChartJS.register(LinearScale, PointElement, Tooltip, Legend);

原图表配置

const data = {
  datasets: [
    {
      label: "TheDataset1",
      data: theDataArray1,
      backgroundColor: "#782D2D",
    },
  ],
};

const options = {
  scales: {
    x: {
      type: "time",
    },
    y: {
      beginAtZero: true,
    },
  },
};

原React渲染代码

<Bubble options={options} data={data} />

解决步骤

1. 确认依赖安装完整

确保已安装所有必需依赖:

npm install chart.js react-chartjs-2 chartjs-adapter-date-fns date-fns
# 或使用yarn
yarn add chart.js react-chartjs-2 chartjs-adapter-date-fns date-fns

2. 导入并注册TimeScale

Chart.js v3+版本中,time类型的刻度需要单独导入TimeScale模块并注册,修改导入代码如下:

import {
  Chart as ChartJS,
  LinearScale,
  PointElement,
  Tooltip,
  Legend,
  // 新增:导入TimeScale模块
  TimeScale,
} from "chart.js";
import "chartjs-adapter-date-fns";
import { Bubble } from "react-chartjs-2";

// 新增:注册TimeScale
ChartJS.register(LinearScale, PointElement, Tooltip, Legend, TimeScale);

3. 验证数据格式

确保theDataArray1中的数据符合时间轴要求,每个气泡数据点需包含x(支持Date对象、时间戳或ISO字符串)、y和r(气泡半径)字段,示例:

const theDataArray1 = [
  { x: new Date("2024-01-01"), y: 10, r: 5 },
  { x: 1704067200000, y: 20, r: 8 },
  { x: "2024-01-03T00:00:00Z", y: 15, r: 6 },
];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:55:18