Skip to content

fix: use Call instead of Get+Invoke in fetch to preserve this for service bindings#190

Merged
syumai merged 1 commit intosyumai:mainfrom
akinazuki:fix/service-binding-fetch-illegal-invocation
Mar 1, 2026
Merged

fix: use Call instead of Get+Invoke in fetch to preserve this for service bindings#190
syumai merged 1 commit intosyumai:mainfrom
akinazuki:fix/service-binding-fetch-illegal-invocation

Conversation

@akinazuki
Copy link
Contributor

Problem

When using WithBinding to call a Cloudflare Service Binding's fetch method, the current implementation throws:

panic: JavaScript error: Illegal invocation: function called with incorrect `this` reference.

This happens because bind.go detaches the method before calling it:

fetchFunc := namespace.Get("fetch")  // detaches method from object
promise := fetchFunc.Invoke(...)     // this === undefined → Illegal invocation

In JavaScript, obj.method() and const f = obj.method; f() behave differently. The latter loses this, which is required for service binding methods to identify the target Worker.

Fix

Replace Get("fetch").Invoke(...) with Call("fetch", ...), which is equivalent to namespace.fetch(...) in JavaScript and preserves the correct this reference:

promise := namespace.Call("fetch", jsReq, init.ToJS())

This fix works correctly for both the global fetch (where this is globalThis) and service bindings (where this must be the binding object).

Notes

  • js.Value.Call(m, args...) is equivalent to JS obj.method(args...)this is bound to obj
  • js.Value.Invoke(args...) is equivalent to JS fn(args...)this is undefined in strict mode
  • The existing DurableObjectStub.Fetch in dostub.go already uses .Call("fetch", ...) correctly; this aligns fetch/bind.go with that pattern

Using namespace.Get("fetch").Invoke(...) detaches the method from its
object, causing "Illegal invocation: function called with incorrect
`this` reference" when used with Cloudflare Service Bindings.

Replace with namespace.Call("fetch", ...), which is equivalent to
namespace.fetch(...) in JavaScript and preserves the correct `this`
reference. This aligns with the existing pattern used in dostub.go.
Copy link
Owner

@syumai syumai left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@syumai syumai merged commit 06859bd into syumai:main Mar 1, 2026
2 checks passed
@akinazuki akinazuki deleted the fix/service-binding-fetch-illegal-invocation branch March 1, 2026 06:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants