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

切换下拉选项生成多幅Apache Echarts时出现初始化问题

解决ECharts「There is a chart instance already initialized on the dom」错误

问题根源

你之前的代码用全局变量myChart追踪实例,存在两个核心问题:

  1. 全局变量仅能记录一个实例,若多个容器调用该函数,实例会被覆盖;
  2. 切换图表类型时,无法精准判断当前目标容器上是否已存在实例,导致重复初始化报错。

ECharts官方推荐通过DOM元素直接获取对应实例,而非依赖全局变量。

修正方案

修改独立.js文件中的createChartLineCat函数,使用echarts.getInstanceByDom获取目标容器的已有实例,再进行销毁/重建操作:

someNameECharts.createChartLineCat = function(config) {
    // 获取目标DOM容器
    const dom = document.getElementById(config.bindTo);
    if (!dom) return; // 容器不存在则直接返回

    // 检查容器上是否已有图表实例
    const existingChart = echarts.getInstanceByDom(dom);
    if (existingChart) {
        existingChart.dispose(); // 销毁已有实例,避免重复初始化
    }

    // 初始化新的图表实例
    const myChart = echarts.init(dom, null, {width: config.width, height: config.height});

    /// 省略部分代码 ////

    let option = {
        title: {
          text: config.title
        },
        toolbox: {
            feature: {
                dataZoom: {},
                saveAsImage: {},
                magicType: {
                type: ['line', 'bar', 'stack']
                }
            }
        },
        color: colorSchema,
        dataset: [
            {
                dimensions: [{name: keyNames[0], type:'ordinal'}, {name: keyNames[1]}, {name: keyNames[2]}],
                source: config.graphData,                
            },              
        ],
        tooltip: {},
        grid: {
          width: '70%',
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        legend: {
            orient: 'vertical',
            right: 10,
            top: 'center',
            },
        xAxis: {
            type: 'category',
            },
        yAxis: {
            type: 'value',
        },
        series: seriesSettings
    };

    outputDataset.forEach(function(ds) {
      option.dataset.push(ds);
    });
        
    myChart.setOption(option);
}

额外说明

  • 无需在switch分支中添加myChart.clear()或清空容器的代码,函数内部已处理实例冲突;
  • 若图表类型差异较小,可将dispose()替换为clear()后直接调用setOption,保留实例并更新配置;
  • 移除原代码中全局的let myChart声明,避免不必要的全局变量污染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 02:27:40