Google Analytics:警告:无法对未安装的组件执行 React 状态更新

Google Analytics: Warning: Can't perform a React state update on an unmounted component

我正在尝试使用指南 found here 将 Google Analytics 添加到 React。

我有

import React, { useEffect } from "react";
import ReactGA from "react-ga";

ReactGA.initialize("UA-0000000-0");

export default (WrappedComponent, options = {}) => {
  const trackPage = page => {
    ReactGA.set({
      page,
      ...options
    });
    ReactGA.pageview(page);
  };

  const HOC = props => {
    useEffect(() => trackPage(props.location.pathname), [
      props.location.pathname
    ]);

    return <WrappedComponent {...props} />;
  };

  return HOC;
};

那么,我这样称呼它:

<BrowserRouter className={classes.root}>
        <Switch>
          <Route path="/login" component={withTracker(Login)} />
          <Route path="/signup" component={withTracker(SignUp)} />
</Switch>
      </BrowserRouter>

完整错误:

react_devtools_backend.js:2273 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.
    in SignIn (at GoogleAnalytics.js:64)
    in HOC (created by Context.Consumer)

我已经尝试使用他们显示的 react hooks 方法以及该页面上建议的其他方法,但仍然出现相同的错误。我是 React 的新手,所以很难找到问题所在。

谢谢!

在卸载组件时尝试在 ReactGA.set 中设置状态会发出该警告。您可以在 useEffect 中将变量 'Mounted' 设置为 true,在 return 函数中将其设置为 false,在组件卸载时执行。

const HOC = props => {
  useEffect(() => {
    let isMounted = true
    isMounted &&        
    trackPage(props.location.pathname)
    return () => isMounted = false
 }, [props.location.pathname]);

  

如果仍然收到警告,请在 useEffect 中移动 ReactGA.set 并使用 Mounted && ReactGA.set.....