fix: use Call instead of Get+Invoke in fetch to preserve this for service bindings#190
Merged
syumai merged 1 commit intosyumai:mainfrom Mar 1, 2026
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
When using
WithBindingto call a Cloudflare Service Binding'sfetchmethod, the current implementation throws:This happens because
bind.godetaches the method before calling it:In JavaScript,
obj.method()andconst f = obj.method; f()behave differently. The latter losesthis, which is required for service binding methods to identify the target Worker.Fix
Replace
Get("fetch").Invoke(...)withCall("fetch", ...), which is equivalent tonamespace.fetch(...)in JavaScript and preserves the correctthisreference:This fix works correctly for both the global
fetch(wherethisisglobalThis) and service bindings (wherethismust be the binding object).Notes
js.Value.Call(m, args...)is equivalent to JSobj.method(args...)—thisis bound toobjjs.Value.Invoke(args...)is equivalent to JSfn(args...)—thisisundefinedin strict modeDurableObjectStub.Fetchindostub.goalready uses.Call("fetch", ...)correctly; this alignsfetch/bind.gowith that pattern