Skip to content

[use-timeout] avoid window usage in SSR #13828

@accardo

Description

@accardo

重现链接

element-plus/element-plus#23907

Vant 版本

4.9.24

描述一下你遇到的问题。

element-plus/element-plus#23907

Problem
use-timeout used window.setTimeout and window.clearTimeout. In SSR (Node) environment, window may be undefined, which can throw during scope dispose and break server rendering.

Solution
Replace window.setTimeout / window.clearTimeout with global setTimeout / clearTimeout
Use ReturnType for cross-environment timer handle typing
Add undefined guard in cancelTimeout and reset handle after cancel
Tests
Add SSR-like test case where window is stubbed as undefined
Ensure cleanup in test always restores globals via try/finally
Verified:
pnpm vitest run packages/hooks/tests/use-timeout.test.ts
pnpm vitest run packages/hooks/tests
Summary by CodeRabbit
Tests

Added tests covering Node/SSR and no-browser-global scenarios to ensure timeouts are not invoked during server rendering and are properly cleaned up.
Bug Fixes

Made timeout registration and cancellation more robust so cancellations safely no-op when no timer exists and callbacks are prevented after scope teardown, including in non-browser environments.

重现步骤

Image Imagevue3.5.31 官方修复了这个问题。导致了use-timeout在 ssr阶段 执行了window.clearTimeout 报错。

设备/浏览器

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions