Skip to content

fix: prevent memory leaks in table and sticky scroll components #1288

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 5 commits into
base: antd-5.x
Choose a base branch
from

Conversation

afc163
Copy link
Member

@afc163 afc163 commented Jun 3, 2025

让 cursor 帮忙修复了一下可能的内存泄漏问题。

close #1266
close ant-design/ant-design#53506

Copy link

vercel bot commented Jun 3, 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 Jun 3, 2025 10:27am

Copy link

coderabbitai bot commented Jun 3, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

@afc163 afc163 requested a review from Copilot June 3, 2025 04:00
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 fixes potential memory leaks by ensuring that event listeners in the StickyScrollBar and Table components are properly cleaned up.

  • In StickyScrollBar, new refs are added to track the previous container and scroll parents and their associated event listeners are cleaned up before adding new ones.
  • In Table, an unmountedRef is introduced to prevent state updates after the component has unmounted.

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
src/stickyScrollBar.tsx Adds cleanup for previous event listeners by tracking the last container and scroll parents.
src/Table.tsx Introduces an unmountedRef to prevent delayed operations on an unmounted component.
Comments suppressed due to low confidence (1)

src/stickyScrollBar.tsx:159

  • For consistency and clarity, consider explicitly passing the capture option (false) to removeEventListener, as is done with addEventListener.
lastScrollParentsRef.current.forEach(p => p.removeEventListener('scroll', checkScrollBarVisible),

return () => {
scrollParents.forEach(p => p.removeEventListener('scroll', checkScrollBarVisible));
window.removeEventListener('resize', checkScrollBarVisible);
window.removeEventListener('scroll', checkScrollBarVisible);
container.removeEventListener('scroll', checkScrollBarVisible);
};
}, [container]);
}, [container, scrollBodyRef.current]);
Copy link
Preview

Copilot AI Jun 3, 2025

Choose a reason for hiding this comment

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

Using a mutable ref value (scrollBodyRef.current) in the dependency array may not trigger updates as expected; consider verifying that the effect is rerun when intended or refactoring to use a stable state or ref object.

Suggested change
}, [container, scrollBodyRef.current]);
}, [container, scrollBodyNode]);

Copilot uses AI. Check for mistakes.

Copy link
Member Author

Choose a reason for hiding this comment

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

@coderabbitai 看看这个回复合理么?

Copy link

Choose a reason for hiding this comment

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

@afc163 Copilot 的建议是合理的,但解决方案有问题。

问题分析:

  1. ✅ Copilot 正确指出了问题:scrollBodyRef.current 是可变的 ref 值,React 不会追踪其变化
  2. ✅ 当 scrollBodyRef.current 变化但 container 不变时,useEffect 不会重新运行
  3. ❌ 但建议的 scrollBodyNode 变量在代码中并不存在

更好的解决方案:

// 选项1:移除 scrollBodyRef.current 依赖
}, [container]);

// 选项2:使用 callback ref 替代
const [scrollBodyNode, setScrollBodyNode] = React.useState<HTMLDivElement | null>(null);
const scrollBodyCallback = React.useCallback((node: HTMLDivElement) => {
  setScrollBodyNode(node);
}, []);

// 然后在依赖中使用 scrollBodyNode
}, [container, scrollBodyNode]);

推荐选项1,因为:

  • effect 内部已有 if (!scrollBodyRef.current) return; 的检查
  • 滚动容器变化时通常意味着整个组件重新渲染,scrollBodyRef 也会相应更新
  • 避免了不必要的复杂性

Copilot 识别了真实问题,但提供的解决方案需要改进。

Copy link

codecov bot commented Jun 3, 2025

Codecov Report

Attention: Patch coverage is 96.15385% with 3 lines in your changes missing coverage. Please review.

Project coverage is 97.77%. Comparing base (8e6e892) to head (9eb36a5).

Files with missing lines Patch % Lines
src/stickyScrollBar.tsx 62.50% 3 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##           antd-5.x    #1288      +/-   ##
============================================
- Coverage     97.78%   97.77%   -0.02%     
============================================
  Files            77       77              
  Lines          7594     7669      +75     
  Branches       1153     1161       +8     
============================================
+ Hits           7426     7498      +72     
- Misses          162      165       +3     
  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.

@yoyo837
Copy link
Member

yoyo837 commented Jun 3, 2025

#1266 要做的是同一件事?

@afc163
Copy link
Member Author

afc163 commented Jun 3, 2025

@yoyo837 看上去是的。

@afc163
Copy link
Member Author

afc163 commented Jun 3, 2025

看上去 src/FixedHolder/index.tsx 里没啥问题。


我已详细检查了 src/FixedHolder/index.tsx 的实现,结论如下:


1. 事件监听与清理

  • 只在 useEffect 里绑定了 wheel 事件到 scrollRef.current,并在 return 时做了 remove:
    React.useEffect(() => {
      function onWheel(e: WheelEvent) {
        const { currentTarget, deltaX } = e as unknown as React.WheelEvent<HTMLDivElement>;
        if (deltaX) {
          onScroll({ currentTarget, scrollLeft: currentTarget.scrollLeft + deltaX });
          e.preventDefault();
        }
      }
      scrollRef.current?.addEventListener('wheel', onWheel, { passive: false });
    
      return () => {
        scrollRef.current?.removeEventListener('wheel', onWheel);
      };
    }, []);
  • 依赖数组为空,意味着只在挂载和卸载时绑定/解绑,不会重复绑定,也不会遗漏解绑。

2. 其它副作用

  • 没有 setTimeout、setInterval、raf、全局事件监听等其它副作用。
  • 其它都是纯渲染逻辑和 memo 计算。

3. ref 传递

  • setScrollRef 用于合并 ref,没问题。

结论

FixedHolder 组件本身没有内存泄漏问题。

  • 事件监听和清理是成对的,且只针对自身 DOM。
  • 没有全局副作用或未清理的定时器/raf。

你可以放心使用。如果有特殊场景(如频繁 mount/unmount 或动态切换 ref),也不会有泄漏风险。如需进一步排查其它细节或组件,欢迎继续指定!


scrollParents.forEach(p => p.addEventListener('scroll', checkScrollBarVisible, false));
window.addEventListener('resize', checkScrollBarVisible, false);
window.addEventListener('scroll', checkScrollBarVisible, false);
container.addEventListener('scroll', checkScrollBarVisible, false);

// 清理上一次 container 的事件监听
if (lastContainerRef.current && lastContainerRef.current !== container) {
Copy link
Member

Choose a reason for hiding this comment

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

看起来不需要 lastContainerRef,在 effect 里记录这个值就行了?

Copy link
Member Author

Choose a reason for hiding this comment

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

@coderabbitai 你看如何,帮着改一下?

Copy link

Choose a reason for hiding this comment

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

@afc163 你好!zombieJ 的建议是正确的。由于 useEffect 的依赖包含了 [container],当 container 改变时整个 effect 会重新运行,清理函数会自动移除之前 container 的事件监听器,所以确实不需要 lastContainerRef

以下是修改建议:

const StickyScrollBar: React.ForwardRefRenderFunction<unknown, StickyScrollBarProps> = (
  { scrollBodyRef, onScroll, offsetScroll, container, direction },
  ref,
) => {
  const prefixCls = useContext(TableContext, 'prefixCls');
  const bodyScrollWidth = scrollBodyRef.current?.scrollWidth || 0;
  const bodyWidth = scrollBodyRef.current?.clientWidth || 0;
  const scrollBarWidth = bodyScrollWidth && bodyWidth * (bodyWidth / bodyScrollWidth);

  const scrollBarRef = React.useRef<HTMLDivElement>();
  const [scrollState, setScrollState] = useLayoutState<{
    scrollLeft: number;
    isHiddenScrollBar: boolean;
  }>({
    scrollLeft: 0,
    isHiddenScrollBar: true,
  });
  const refState = React.useRef<{
    delta: number;
    x: number;
  }>({
    delta: 0,
    x: 0,
  });
  const [isActive, setActive] = React.useState(false);
  const rafRef = React.useRef<number | null>(null);
  // 记录上一次的 scrollParents
  const lastScrollParentsRef = React.useRef<(HTMLElement | SVGElement)[]>([]);

  // ... 其他代码保持不变 ...

  // Loop for scroll event check
  React.useEffect(() => {
    if (!scrollBodyRef.current) {
      return;
    }

    // 清理上一次 scrollParents 的事件监听
    lastScrollParentsRef.current.forEach(p =>
      p.removeEventListener('scroll', checkScrollBarVisible),
    );

    const scrollParents: (HTMLElement | SVGElement)[] = [];
    let parent = getDOM(scrollBodyRef.current);
    while (parent) {
      scrollParents.push(parent);
      parent = parent.parentElement;
    }
    lastScrollParentsRef.current = scrollParents;

    scrollParents.forEach(p => p.addEventListener('scroll', checkScrollBarVisible, false));
    window.addEventListener('resize', checkScrollBarVisible, false);
    window.addEventListener('scroll', checkScrollBarVisible, false);
    container.addEventListener('scroll', checkScrollBarVisible, false);

    return () => {
      scrollParents.forEach(p => p.removeEventListener('scroll', checkScrollBarVisible));
      window.removeEventListener('resize', checkScrollBarVisible);
      window.removeEventListener('scroll', checkScrollBarVisible);
      container.removeEventListener('scroll', checkScrollBarVisible);
    };
  }, [container]);

  // ... 其他代码保持不变 ...
};

主要变更:

  1. 移除了 lastContainerRef 的声明
  2. 移除了手动清理之前 container 事件监听器的代码
  3. 保留了 lastScrollParentsRef 因为 scrollParents 的清理逻辑仍然需要

这样的修改更简洁,也避免了重复的事件监听器清理逻辑。

🐰💡
∩───∩
( ◕ ◕ )
│ ∩─∩ │
└─┘ └─┘

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.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

@@ -149,14 +151,22 @@ const StickyScrollBar: React.ForwardRefRenderFunction<unknown, StickyScrollBarPr

// Loop for scroll event check
React.useEffect(() => {
if (!scrollBodyRef.current) return;
if (!scrollBodyRef.current) {
Copy link
Member

Choose a reason for hiding this comment

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

这里没括号原来是为了满足覆盖率啊 😂

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.

3 participants