DEBUG.WIKI
IPPeak:从目标地区访问网页,住宅代理、SEO 监测、广告验证
阿里云;从建站到云上业务;云服务器 · 数据库 · 对象存储;查看产品 →
搬瓦工;先看线路,再选 VPS;CN2 GIA · 对应线路套餐;查看线路 →

解决 Single-SPA 报错 Custom props function binding lost 函数上下文丢失修复

排查 主应用通过 Single-SPA customProps 向子应用传递通信函数(如 onGlobalStateChange)时,子应用调用报 TypeError: Cannot read properties of undefined,分析 函数上下文绑定与代理序列化。

问题现象

子应用尝试调用主应用传入的全局状态变更函数时,控制台抛出未定义异常:

TypeError: Cannot read properties of undefined (reading 'stateHub')
    at dispatchChange (host-app.js:82:10)
    at Object.onGlobalStateChange (sub-app.js:25:9)

触发根因

  1. 主应用在向 customProps 挂载业务类的方法时,直接传递了裸函数引用(如 customProps: { notify: this.notify });
  2. 当子应用从自身的全局上下文调用该函数时,JavaScript this 上下文绑定丢失(变为 undefined 或 window);
  3. 主应用内部读取 this.stateHub 失败触发致命异常。

解决步骤

在主应用传递自定义属性函数时使用箭头函数或显式 bind 锁定上下文

规范属性传递:

registerApplication({
  name: 'sub-app-1',
  app: () => import('./sub-app.js'),
  activeWhen: '/app1',
  customProps: {
    notify: (msg) => this.handleNotify(msg),
    dispatchChange: this.dispatchChange.bind(this),
  },
});

采用现代事件总线或 RxJS Subject 进行主子应用解耦通信

避免直接传递强依赖实例内部上下文的成员函数。

验证确认

重新调用跨应用通信:

子应用传参顺畅到达主应用状态机,this 上下文稳定绑定,数据实时双向同步。