Skip to content

Fix memory leak #1266

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open

Conversation

mix0000
Copy link

@mix0000 mix0000 commented May 7, 2025

I found a complicated memery leak problem which caused by src/FixedHolder/index.tsx

Inside main useEffect component adds listener to scrollRef. In code everything looks okay but in production removeEventListener is never being called.

Here is the snapshot from memory inspector:
image_2025-05-07_14-49-24

To detect the problem I patched node_modules files and add console.logs.

image_2025-05-07_14-46-03

As you see "remove listener" log is never being called even though "before remove" log is called

image_2025-05-07_14-50-00

Summary by CodeRabbit

  • 优化
    • 改进了滚动和鼠标事件监听的清理机制,采用更安全的自动移除方式,提升组件的稳定性和性能。

Muhammed Teuvazhukov added 2 commits May 7, 2025 15:13
 - This commit fixes the main problem with memory leak
 - Also, this ensures proper cleanup of the event listener by aborting it with a signal. It improves reliability and prevents potential memory leaks or unexpected behavior
 - Change other addEventListeners to AbortController way for same code style across listeners
Copy link

vercel bot commented May 7, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
table ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 12, 2025 6:20am

Copy link

coderabbitai bot commented May 7, 2025

Walkthrough

此次更改主要将事件监听器的注册与清理方式由手动添加和移除,统一替换为使用 AbortController 的 signal 选项进行管理。涉及的事件包括滚轮、鼠标、滚动和窗口尺寸变化等。组件卸载或 effect 重新执行时,通过调用 abort 方法自动移除所有相关监听器,逻辑与事件处理函数本身未发生变化。

Changes

文件/文件组 变更摘要
src/FixedHolder/index.tsx 使用 AbortController 管理 'wheel' 事件监听器,替换手动移除逻辑。
src/stickyScrollBar.tsx 用 AbortController 管理鼠标、滚动和窗口相关事件监听及清理流程。

Possibly related PRs

  • fix: sticky event loop by Copilot AI #1231:同样涉及 src/stickyScrollBar.tsx 事件监听管理的优化,关注点为多父元素的滚动事件监听与检测逻辑改进,与本次 PR 在文件和事件管理方式上有直接关联。

Poem

🐇
监听器如风,随手即来去,
AbortController 轻松解烦忧。
不必手动清理旧,
一声 abort 万事休。
代码整洁心欢喜,
兔子跳跃庆新秋!

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

src/FixedHolder/index.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the config "prettier" to extend from. Please check that the name of the config is correct.

The config "prettier" was referenced from the config file in "/.eslintrc.js".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.

src/stickyScrollBar.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the config "prettier" to extend from. Please check that the name of the config is correct.

The config "prettier" was referenced from the config file in "/.eslintrc.js".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8078217 and e971bb1.

📒 Files selected for processing (2)
  • src/FixedHolder/index.tsx (2 hunks)
  • src/stickyScrollBar.tsx (2 hunks)
🔇 Additional comments (3)
src/FixedHolder/index.tsx (1)

84-117: 使用 AbortController 优化事件监听器清理,解决内存泄漏问题

通过将原有的手动添加和移除事件监听器的方式改为使用 AbortController 的 signal 选项,您有效地解决了内存泄漏问题。这种变更确保了组件卸载时事件监听器能够被正确地移除。

具体优点:

  1. 使用 AbortController 提供了更可靠的事件清理机制
  2. 避免了 React 组件生命周期中由于某些原因导致的清理函数未被调用的情况
  3. 在异步操作和并发渲染时表现更加稳定

这种方法是修复事件监听器相关内存泄漏的现代最佳实践。

src/stickyScrollBar.tsx (2)

143-157: 使用 AbortController 优化鼠标事件监听器清理

将鼠标事件(mouseup 和 mousemove)的监听器管理方式更新为使用 AbortController 及其 signal 选项是非常合适的改进。这种方式比手动调用 removeEventListener 更加可靠,尤其是在 React 组件的复杂生命周期中。

此更改与 FixedHolder 组件中的修复保持一致,使代码库中事件监听器的管理更加统一。


160-193: 使用 AbortController 优化滚动和调整大小事件监听器清理

对于滚动父元素、窗口和容器的事件监听器清理方式的改进非常到位。使用单个 AbortController 来管理多个事件监听器,通过一次 abort() 调用清理所有监听器,简化了代码并增强了可靠性。

此更改特别重要,因为该组件注册了多个事件监听器(滚动和调整大小)到多个元素上,使用 AbortController 极大地简化了清理过程,有效防止了内存泄漏。

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

scrollParents.forEach(p =>
p.addEventListener(SCROLL_EVENT, checkScrollBarVisible, {
capture: false,
signal: abortController.signal,
Copy link
Member

Choose a reason for hiding this comment

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

The compatibility requirements for using signal are too high

Copy link
Member

Choose a reason for hiding this comment

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

Copy link

Choose a reason for hiding this comment

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

🧩 Analysis chain

@yoyo837 您提出的关于 signal 参数兼容性要求过高的问题是很有道理的。根据最新的兼容性数据,addEventListenersignal 参数支持是比较新的特性:

  • Chrome 88+ (2021年1月)
  • Firefox 68+ (2019年7月)
  • Safari 15.4+ (2022年3月)
  • Edge 88+ (2021年1月)

对于一个广泛使用的组件库来说,这确实可能带来兼容性问题。以下是可能的替代方案:

  1. 保持使用传统的 removeEventListener 方式,但确保在组件卸载时正确清理:
React.useEffect(() => {
  // 添加事件监听
  scrollParents.forEach(p => 
    p.addEventListener(SCROLL_EVENT, checkScrollBarVisible, false));
  window.addEventListener(RESIZE_EVENT, checkScrollBarVisible, false);
  window.addEventListener(SCROLL_EVENT, checkScrollBarVisible, false);
  container.addEventListener(SCROLL_EVENT, checkScrollBarVisible, false);

  // 返回清理函数
  return () => {
    scrollParents.forEach(p => 
      p.removeEventListener(SCROLL_EVENT, checkScrollBarVisible, false));
    window.addEventListener(RESIZE_EVENT, checkScrollBarVisible, false);
    window.addEventListener(SCROLL_EVENT, checkScrollBarVisible, false);
    container.removeEventListener(SCROLL_EVENT, checkScrollBarVisible, false);
  };
}, [container]);
  1. 使用特性检测进行优雅降级:
React.useEffect(() => {
  const supportsAbortController = typeof AbortController === 'function';
  const abortController = supportsAbortController ? new AbortController() : null;
  const options = supportsAbortController 
    ? { capture: false, signal: abortController.signal }
    : false;

  scrollParents.forEach(p => 
    p.addEventListener(SCROLL_EVENT, checkScrollBarVisible, options));
  // ... 添加其他事件监听
  
  return () => {
    if (supportsAbortController) {
      abortController.abort();
    } else {
      scrollParents.forEach(p => 
        p.removeEventListener(SCROLL_EVENT, checkScrollBarVisible, false));
      // ... 移除其他事件监听
    }
  };
}, [container]);

您认为哪种方案更适合当前的项目需求?


🌐 Web query:

What browsers support AbortController signal with addEventListener?

💡 Result:

The AbortController's signal property can be used with addEventListener to manage event listeners that can be aborted. This feature is supported in the following browsers and versions:

  • Chrome: Version 88 and later
  • Edge: Version 88 and later
  • Firefox: Version 86 and later
  • Opera: Version 76 and later

In these versions, you can associate an event listener with an AbortSignal by passing the signal as an option in the addEventListener method. This allows you to abort the event listener by calling controller.abort(). (barker.codes)

However, this functionality is not supported in Safari, Safari on iOS, or Opera for Android. (barker.codes)

For browsers that do not support this feature, you can use a polyfill to achieve similar functionality. (barker.codes)

Citations:


🌐 Web query:

When was AbortController signal support added to addEventListener and what is the browser compatibility?

💡 Result:

When Was AbortController Signal Support Added to addEventListener?

Support for using an AbortSignal (via an AbortController) as part of the addEventListener options object was first introduced in Chromium-based browsers. Specifically, Chrome added this feature in version 88, released in January 2021, with default support enabled in Chrome 90 (April 2021)[4][2]. The feature allows developers to automatically remove event listeners when the associated AbortSignal is aborted, simplifying cleanup and reducing memory leaks.

Other browsers followed suit:

  • Firefox implemented support around version 86 (released February 2021)[4].
  • Safari added support in version 15 (released in September 2021)[4].

Browser Compatibility

Browser Minimum Version with Support Notes
Chrome 88 (flag), 90 (default) Full support from 90[4]
Firefox 86 Full support[4]
Safari 15 Full support[4]
Edge Follows Chromium (90+) Full support
iOS Safari 15 Full support[4]
Older Browsers Not supported Polyfills are available[4]
  • Before these versions, while AbortController and AbortSignal were available for fetch and some other APIs, they could not be used with addEventListener.
  • For unsupported browsers (such as Safari 14 or below), developers can use polyfills to simulate this functionality[4].

Usage Example

const controller = new AbortController();
const signal = controller.signal;

element.addEventListener('click', handler, { signal });
// Later, automatically removes the handler:
controller.abort();

Summary

  • Specification: The signal property in addEventListener options allows passing an AbortSignal. When aborted, the event listener is removed automatically[2][4][9].
  • Chrome: Supported from 88 (behind flag), 90+ by default[4][2].
  • Firefox: Supported from version 86[4].
  • Safari: Supported from version 15[4].
  • Polyfills: Available for Safari 14 and other unsupported browsers[4].

This feature is now broadly available in all major evergreen browsers from early 2021 onwards, making automatic listener cleanup much easier across web applications.

Citations:


@yoyo837 您提出的关于signal参数兼容性问题非常有价值。根据最新的浏览器兼容性数据,addEventListenersignal选项是相对较新的特性:

  • Chrome: 88版本(2021年1月)开始支持,90版本默认启用
  • Firefox: 86版本(2021年2月)开始支持
  • Safari: 15版本(2021年9月)开始支持
  • Edge: 遵循Chromium(90+)

对于需要广泛兼容性的React组件库,这确实可能带来问题。以下是几种替代方案:

  1. 传统的removeEventListener方式,确保正确清理:
React.useEffect(() => {
  scrollParents.forEach(p => 
    p.addEventListener(SCROLL_EVENT, checkScrollBarVisible, false));
  window.addEventListener(RESIZE_EVENT, checkScrollBarVisible, false);
  window.addEventListener(SCROLL_EVENT, checkScrollBarVisible, false);
  container.addEventListener(SCROLL_EVENT, checkScrollBarVisible, false);

  return () => {
    scrollParents.forEach(p => 
      p.removeEventListener(SCROLL_EVENT, checkScrollBarVisible, false));
    window.removeEventListener(RESIZE_EVENT, checkScrollBarVisible, false);
    window.removeEventListener(SCROLL_EVENT, checkScrollBarVisible, false);
    container.removeEventListener(SCROLL_EVENT, checkScrollBarVisible, false);
  };
}, [container]);
  1. 特性检测方式:
React.useEffect(() => {
  const supportsAbortController = typeof AbortController === 'function' && 
                                 'signal' in AbortController.prototype;
  const abortController = supportsAbortController ? new AbortController() : null;
  const options = supportsAbortController 
    ? { capture: false, signal: abortController.signal }
    : false;

  // 添加事件监听
  scrollParents.forEach(p => 
    p.addEventListener(SCROLL_EVENT, checkScrollBarVisible, options));
  // ...其他事件监听
  
  return () => {
    if (supportsAbortController) {
      abortController.abort();
    } else {
      scrollParents.forEach(p => 
        p.removeEventListener(SCROLL_EVENT, checkScrollBarVisible, false));
      // ...其他事件移除
    }
  };
}, [container]);

您认为哪种解决方案更适合当前项目的需求和兼容性目标?


✏️ Learnings added
Learnt from: yoyo837
PR: react-component/table#1266
File: src/stickyScrollBar.tsx:174-174
Timestamp: 2025-05-08T01:01:54.659Z
Learning: AbortController and its signal parameter with addEventListener have high browser compatibility requirements. The signal option for addEventListener was added in Chrome 88+ (Jan 2021), Firefox 68+ (July 2019), Safari 15.4+ (March 2022), and Edge 88+ (Jan 2021). For wider browser support, traditional removeEventListener cleanup is preferred.

Learnt from: yoyo837
PR: react-component/table#1266
File: src/stickyScrollBar.tsx:174-174
Timestamp: 2025-05-08T01:01:54.659Z
Learning: AbortController and its signal parameter with addEventListener have high browser compatibility requirements. The signal option for addEventListener was added in Chrome 88+ (Jan 2021), Firefox 86+ (Feb 2021), Safari 15+ (Sept 2021), and Edge 88+ (Jan 2021). For wider browser support, traditional removeEventListener cleanup is preferred.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Copy link

codecov bot commented May 8, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 98.03%. Comparing base (8078217) to head (e971bb1).

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #1266   +/-   ##
=======================================
  Coverage   98.03%   98.03%           
=======================================
  Files          76       76           
  Lines        7425     7447   +22     
  Branches     1146     1145    -1     
=======================================
+ Hits         7279     7301   +22     
  Misses        140      140           
  Partials        6        6           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@afc163 afc163 requested review from zombieJ and Copilot May 8, 2025 02:25
Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR addresses a memory leak issue by updating event listener cleanup in two components using AbortController, ensuring that all event listeners are automatically removed when the component unmounts or dependencies change.

  • Replaces manual removeEventListener calls with AbortController.abort() in src/stickyScrollBar.tsx for mouse and scroll events.
  • Updates the wheel event listener in src/FixedHolder/index.tsx to use AbortController for cleanup.

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
src/stickyScrollBar.tsx Updated mouse and scroll event listeners to use AbortController, ensuring proper cleanup.
src/FixedHolder/index.tsx Updated wheel event listener to use AbortController and eliminate the manual removeEventListener call.
Comments suppressed due to low confidence (1)

src/FixedHolder/index.tsx:87

  • [nitpick] Avoid unnecessary type assertion from native WheelEvent to React.WheelEvent. Consider using native event properties directly for improved type safety.
function onWheel(e: WheelEvent) { const { currentTarget, deltaX } = e as unknown as React.WheelEvent<HTMLDivElement>;

scrollRef.current?.addEventListener('wheel', onWheel, { passive: false });
scrollRef.current?.addEventListener('wheel', onWheel, {
passive: false,
signal: abortController.signal,
Copy link
Member

Choose a reason for hiding this comment

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

Before move to signal, seems why removeEventListener not working is much important. If scrollRef.current is not valid when unmount, we can just simply modify as :

const holder = scrollRef.current;

holder?.addEventListener(...)

return () => {
  holder?.removeEventListener(...)
};

Copy link
Author

Choose a reason for hiding this comment

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

If you dont want to move to AbortController it will work as expected. But we have more problems than I thought. In stickyScrollBar.tsx the handlers (onMouseUp, onMouseMove and checkScrollBarVisible) are declared inside the body of the component function, that will also lead to memory leak because after each render the reference for this functions will be re-created and the cleanup function will have reference to the first declaration of this functions and removeEventListener will not work because of mismatching handler references, so looks like we should wrap them to useCallback?? But damn, I'm too scaried to do that because we should properly control the dependencies for this useEffects and combine them with dependencies of another useEffect which also has their own depencies (scrollBarWidth, isActive)

Copy link
Member

Choose a reason for hiding this comment

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

onMouseUp onMouseMove & checkScrollBarVisible are correctly handle with closure for each render. Could you provide a minimun reproduce of this?

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.

4 participants