echarts更新数据后报错 There is a chart instance already initialized on the dom

发布时间 2023-06-01 14:43:22作者: 埃菲尔上的加菲猫

产生原因

使用Echarts插件的时候,多次加载会出现There is a chart instance already initialized on the dom.的警告,表示DOM上已经初始化了一个图表实例。

解决方案

定义一个全局变量,在初始化之前先判断该实例是否存在,若存在,先销毁。

var myChart;//全局变量
function drawChart(){
    if (myChart != null && myChart != "" && myChart != undefined) {
        myChart.dispose();//销毁
    }
    myChart = echarts.init(document.getElementById('id'));//初始化
    const option = {
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
            type: 'value'
        },
        series: [{
            data: [820, 932, 901, 934, 1290, 1330, 1320],
            type: 'line',
            areaStyle: {}
        }]
    };
    option && myChart.setOption(option);
}

来源:(25条消息) [问题解决]Echarts:There is a chart instance already initialized on the dom._-olivia-的博客-CSDN博客