clearInterval在componentWillUnmount中不起作用

时间:2018-11-29 06:53:20

标签: javascript reactjs

我的React应用程序在componentDidMount中获取api和setInterval并在componentWillUnmount中将其删除,但是即使组件不再挂载(例如,当用户注销并重定向到登录页面时),它仍然会定期执行fetch api,如何对其进行调试?

(1)获取api代码

fetchApi = async pathname => {
const URL = 'API URL'
try {
  const { data } = await axios.get(URL, { withCredentials: true });
  const { updateTime, results } = data;
  const sortedResults = _.sortBy(results, "wo_start").reverse();

  // fetching user data from sessionStorage
  const user = JSON.parse(sessionStorage.getItem("user"));
  if (!user) {
    return this.setState({
      redirectToLogin: true
    });
  }
  return this.setState({
    orders: sortedResults,
    renderedOrders: sortedResults,
    updateTime: updateTime.time,
    pathname,
    user
  });
} catch (e) {
  console.error("Credentials Failed");
  return this.setState({
    redirectToLogin: true
  });
}};

(2)componentDidMount

componentDidMount() {
const { pathname } = this.props.history.location;
this.fetchApi(pathname)
  .then(() => {
    const intervalId = setInterval(
      () => this.fetchApi(pathname),
      2 * 60 * 1000
    );
    this.setState({
      intervalId: intervalId
    })
  })
  .catch(e => console.error(e));
  }

(3)componentWillUnmount

 componentWillUnmount() {
// clearing set interval
clearInterval(this.state.intervalId);
};

(4)这是注销后来自chrome控制台的图像 chrome console after logout

1 个答案:

答案 0 :(得分:0)

setState()是异步的。

更改代码:

(2)componentDidMount

 ...
 ...
  this.fetchApi(pathname)
  .then(() => {
    const intervalId = setInterval(
    () => this.fetchApi(pathname),
    2 * 60 * 1000
  );
  this.intervalId= intervalId
...
...

(3)componentWillUnmount

componentWillUnmount() {
  // clearing set interval
  clearInterval(this.intervalId);
};