无法在转到顶部 btn 时对未安装的组件执行 React 状态更新

Can't perform React state update on an unmounted component on making go to top btn

我正在处理转到顶部按钮组件,但我不明白发生了什么。 isBtnShown 控制按钮的样式

export const TopBtn = () => {
    const [isBtnShown, setIsBtnShown] = useState(false)

    const trackScroll = () => {
        if (!isBtnShown && window.pageYOffset > 400) {
            setIsBtnShown(true)
        } else if (isBtnShown && window.pageYOffset <= 400) {
            setIsBtnShown(false)
        }
    }

    const backToTop = () => {
        if (window.pageYOffset > 0) {
            window.scrollTo({ top: 0, behavior: 'smooth' })
        }
    }
    window.addEventListener('scroll', trackScroll)
    useEffect(() => {
        return () => {
            window.removeEventListener('scroll', trackScroll)
        }
    }, [])
    return (
        <button className={isBtnShown ? `${s.topBtn} ${s.shown}` : `${s.topBtn}`} onClick={backToTop}>
            <ChevronUpIcon />
        </button>
    )
}

这里有错误

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. at TopBtn (http://localhost:4000/src/features/TopBtn/TopBtn.jsx?t=1625128489631:21:39) at div

window.addEventListener('scroll', trackScroll)
    useEffect(() => {
        return () => {
            window.removeEventListener('scroll', trackScroll)
        }
    }, [])

应该是

    useEffect(() => {
        const trackScroll = () => {
            if (!isBtnShown && window.pageYOffset > 400) {
                setIsBtnShown(true)
            } else if (isBtnShown && window.pageYOffset <= 400) {
               setIsBtnShown(false)
            }
        }
        window.addEventListener('scroll', trackScroll)
        return () => {
            window.removeEventListener('scroll', trackScroll)
        }
    }, [isBtnShown])

注意,对 isBtnShown 的依赖,以及 useEffect

中的添加和删除侦听器