You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+TypeScript中setTimeout与useState使用报错及解决(点击切换文本)

问题解决:TypeScript中setTimeout语法错误导致的@typescript-eslint/no-unused-expressions报错

错误根源

你的报错是因为setTimeout的参数写法完全错误:你把延迟时间2000用逗号写在了回调函数内部,这会让2000变成一个孤立的无用表达式,触发ESLint的no-unused-expressions规则。

修正后的完整代码

状态与事件处理逻辑

import { useState } from 'react';

// 组件内部逻辑
const [showCopy, setShowCopy] = useState(false);

const handleClick = () => {
  setShowCopy(true);
  // 正确的setTimeout写法:延迟时间作为第二个参数传入
  setTimeout(() => {
    setShowCopy(false);
  }, 2000);
};

JSX部分

<div 
  onClick={() => {
    navigator.clipboard.writeText("1234");
    handleClick();
  }}
>
  {showCopy ? "you copied the no." : "1234"}
</div>

关键说明

  1. setTimeout的正确用法:setTimeout(回调函数, 延迟毫秒数),延迟时间必须作为第二个参数放在setTimeout的括号里,不能写在回调函数内部。
  2. 你的复制文本逻辑和状态切换的核心逻辑是对的,修正语法后就能正常实现「点击后切换提示语,2秒后恢复原文本」的需求。
  3. 额外优化提示(可选):如果要防止用户重复点击导致状态混乱,可以给handleClick加防抖逻辑,比如用useRef记录定时器ID,每次点击前清除之前的定时器:
const timerRef = useRef<NodeJS.Timeout | null>(null);

const handleClick = () => {
  if (timerRef.current) clearTimeout(timerRef.current);
  setShowCopy(true);
  timerRef.current = setTimeout(() => {
    setShowCopy(false);
    timerRef.current = null;
  }, 2000);
};

内容的提问来源于stack exchange,提问作者Spluli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 01:31:05