Skip to content

Commit b3f526f

Browse files
committed
Fix bug
1 parent e0549a0 commit b3f526f

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

packages/browser/src/helpers.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ export function ignoreNextOnError(): void {
3232
* Instruments the given function and sends an event to Sentry every time the
3333
* function throws an exception.
3434
*
35-
* @param fn A function to wrap.
35+
* @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always
36+
* has a correct `this` context.
3637
* @returns The wrapped function.
3738
* @hidden
3839
*/
@@ -75,8 +76,8 @@ export function wrap(
7576
}
7677

7778
/* eslint-disable prefer-rest-params */
78-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
79-
const sentryWrapped: WrappedFunction = function (this: any): void {
79+
// It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`
80+
const sentryWrapped: WrappedFunction = function (this: unknown): void {
8081
const args = Array.prototype.slice.call(arguments);
8182

8283
try {

packages/browser/src/integrations/trycatch.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,13 @@ function _wrapEventTarget(target: string): void {
208208
): (eventName: string, fn: EventListenerObject, capture?: boolean, secure?: boolean) => void {
209209
try {
210210
if (typeof fn.handleEvent === 'function') {
211-
fn.handleEvent = wrap(fn.handleEvent.bind(fn), {
211+
// ESlint disable explanation:
212+
// First, it is generally safe to call `wrap` with an unbound function. Furthermore, using `.bind()` would
213+
// introduce a bug here, because bind returns a new function that doesn't have our
214+
// flags(like __sentry_original__) attached. `wrap` checks for those flags to avoid unnecessary wrapping.
215+
// Without those flags, every call to addEventListener wraps the function again, causing a memory leak.
216+
// eslint-disable-next-line @typescript-eslint/unbound-method
217+
fn.handleEvent = wrap(fn.handleEvent, {
212218
mechanism: {
213219
data: {
214220
function: 'handleEvent',

0 commit comments

Comments
 (0)