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

TypeScript调用对象挂载的fetch触发WorkerGlobalScope非法调用报错

错误含义与触发原因

这个Illegal invocation错误属于浏览器内置API的执行上下文校验失败:浏览器要求fetch方法运行时内部的this必须指向全局作用域对象(Worker环境下为WorkerGlobalScope,普通页面环境下为window/globalThis),不符合要求时会直接拒绝执行抛出该错误。

你当前代码的问题出在赋值逻辑:直接把globalThis.fetch方法引用赋值给host对象的fetch属性后,执行host.fetch()时,方法内部的this会自动指向host对象而非全局对象,触发了浏览器的fetch调用校验规则。

修复方案

任选以下任意一种即可解决问题:

  • 赋值时给fetch绑定固定的全局上下文
const host: Host = {
    fetch: globalThis.fetch.bind(globalThis),
    // 其余属性
}
  • 用箭头函数包装调用,跳过this绑定逻辑
const host: Host = {
    fetch: (...args) => globalThis.fetch(...args),
    // 其余属性
}
  • 调用时手动指定全局上下文(不推荐,侵入性高)
const response: Response = await host.fetch.call(globalThis, url, ...);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:24:03