TypeError: Illegal invocation: function called with incorrect this reference
I got this error when calling some method from generated api client. when class looks like this:
class API { constructor( options?: { fetch?: typeof fetch; } ) { this.fetch = options?.fetch ?? globalThis.fetch; }}
class API { constructor( options?: { fetch?: typeof fetch; } ) { this.fetch = options?.fetch ?? globalThis.fetch; }}
and doing
(new API()).callMethod()
(new API()).callMethod()
will raise the error. after some searching, I found different context makes this problem and this can be solved by passing fetch to
fetch.bind(globalThis)
fetch.bind(globalThis)
, which binds fetch's context to global context. What I don't understand yet is why API works on browser and node, but Worker needs to bind globalThis to fetch.