Dash图像悬停追踪客户端回调触发reading 'apply'报错如何解决
报错原因
- 你在Python代码中给图像轨迹设置了
hoverinfo='none',导致Plotly不会生成任何hover点位数据,触发回调时传入collect_hoverdata的hover_point参数为undefined,直接调用hover_point.points会抛出未捕获异常,进而触发Dash客户端回调的apply相关报错。 - 你在JS函数里写了
var points = alert(points_array[0]),alert()方法无返回值,points变量值为undefined,后续读取points.x也会抛出异常。 - 所有客户端回调没有做空值兼容,首次加载时输入参数为空也会触发异常。
修复方案
1. 修改Python端图像配置
将url_to_fig函数中关闭hover的代码替换为保留hover点位输出的配置:
# 原代码 # fig.update_traces(hoverinfo='none', hovertemplate=None) # 替换为 fig.update_traces(hovertemplate='<extra></extra>') # 隐藏hover提示框但保留点位数据
2. 修正assets/hovertracker.js代码
补全空值判断,删除错误的alert赋值:
var img_hover_data = []; window.dash_clientside = Object.assign({}, window.dash_clientside, { clientside: { collect_hoverdata: function(hover_point) { // 空值拦截,避免无hover数据时报错 if (!hover_point?.points?.length) { return window.dash_clientside.no_update; } const targetPoint = hover_point.points[0]; img_hover_data.push([ targetPoint.x, targetPoint.y, Date.now() ]); return 0; } } })
3. 修正Next按钮的客户端回调
补全变量声明和空值判断:
app.clientside_callback( """ function(nclicks) { if (nclicks === undefined) return []; const to_return = img_hover_data.slice(); img_hover_data = []; return to_return; } """, Output("hoverdata", "data"), Input('next-button', 'n_clicks') )
内容的提问来源于stack exchange,提问作者acciolurker
相关产品推荐
相关产品推荐

