Google Analytics(分析):警告:无法在已卸载的组件上执行React状态更新

时间:2020-07-29 20:01:23

标签: javascript reactjs google-analytics react-router

我正在尝试使用指南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的新手,所以很难找到问题。

谢谢!

1 个答案:

答案 0 :(得分:1)

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

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

  

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