在React Hooks useEffects中取消Axios REST调用会导致清理失败

时间:2018-12-20 03:08:31

标签: reactjs axios react-hooks

我显然不能正确清理并取消axios GET请求。在我的本地计算机上,我收到一条警告

  

无法在已卸载的组件上执行React状态更新。这是   无操作,但表示您的应用程序内存泄漏。修理,   取消useEffect清理中的所有订阅和异步任务   功能。

在stackblitz上,我的代码有效,但是由于某些原因,我无法单击该按钮来显示错误。它只会始终显示返回的数据。

https://codesandbox.io/s/8x5lzjmwl8

请查看我的代码并找到我的缺陷。

useAxiosFetch.js

import {useState, useEffect} from 'react'
import axios from 'axios'

const useAxiosFetch = url => {
    const [data, setData] = useState(null)
    const [error, setError] = useState(null)
    const [loading, setLoading] = useState(true)

    let source = axios.CancelToken.source()
    useEffect(() => {
        try {
            setLoading(true)
            const promise = axios
                .get(url, {
                    cancelToken: source.token,
                })
                .catch(function (thrown) {
                    if (axios.isCancel(thrown)) {
                        console.log(`request cancelled:${thrown.message}`)
                    } else {
                        console.log('another error happened')
                    }
                })
                .then(a => {
                    setData(a)
                    setLoading(false)
                })
        } catch (e) {
            setData(null)
            setError(e)
        }

        if (source) {
            console.log('source defined')
        } else {
            console.log('source NOT defined')
        }

        return function () {
            console.log('cleanup of useAxiosFetch called')
            if (source) {
                console.log('source in cleanup exists')
            } else {
                source.log('source in cleanup DOES NOT exist')
            }
            source.cancel('Cancelling in cleanup')
        }
    }, [])

    return {data, loading, error}
}

export default useAxiosFetch

index.js

import React from 'react';

import useAxiosFetch from './useAxiosFetch1';

const index = () => {
    const url = "http://www.fakeresponse.com/api/?sleep=5&data={%22Hello%22:%22World%22}";
    const {data,loading} = useAxiosFetch(url);

    if (loading) {
        return (
            <div>Loading...<br/>
                <button onClick={() => {
                    window.location = "/awayfrom here";
                }} >switch away</button>
            </div>
        );
    } else {
        return <div>{JSON.stringify(data)}xx</div>
    }
};

export default index;

4 个答案:

答案 0 :(得分:2)

您遇到的问题是,在快速网络上,请求会导致快速响应,并且不允许您单击按钮。在可以通过ChromeDevTools实现的受限制的网络上,您可以正确地可视化此行为

第二,当您尝试使用window.location.href = 'away link'导航时,react并没有更改以触发/执行组件清理,因此不会触发useEffect的清理功能。

使用路由器作品

import React from 'react'
import ReactDOM from 'react-dom'
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom'

import useAxiosFetch from './useAxiosFetch'

function App(props) {
  const url = 'https://www.siliconvalley-codecamp.com/rest/session/arrayonly'
  const {data, loading} = useAxiosFetch(url)

  // setTimeout(() => {
  //   window.location.href = 'https://www.google.com/';
  // }, 1000)
  if (loading) {
    return (
      <div>
        Loading...
        <br />
        <button
          onClick={() => {
            props.history.push('/home')
          }}
        >
          switch away
        </button>
      </div>
    )
  } else {
    return <div>{JSON.stringify(data)}</div>
  }
}

ReactDOM.render(
  <Router>
    <Switch>
      <Route path="/home" render={() => <div>Hello</div>} />
      <Route path="/" component={App} />
    </Switch>
  </Router>,
  document.getElementById('root'),
)

您可以check the demo在慢速网络上正常工作

答案 1 :(得分:1)

这是最终代码,万一有人回来,一切正常。

import {useState, useEffect} from "react";
import axios, {AxiosResponse} from "axios";

const useAxiosFetch = (url: string, timeout?: number) => {
    const [data, setData] = useState<AxiosResponse | null>(null);
    const [error, setError] = useState(false);
    const [errorMessage, setErrorMessage] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        let unmounted = false;
        let source = axios.CancelToken.source();
        axios.get(url, {
            cancelToken: source.token,
            timeout: timeout
        })
            .then(a => {
                if (!unmounted) {
                    // @ts-ignore
                    setData(a.data);
                    setLoading(false);
                }
            }).catch(function (e) {
            if (!unmounted) {
                setError(true);
                setErrorMessage(e.message);
                setLoading(false);
                if (axios.isCancel(e)) {
                    console.log(`request cancelled:${e.message}`);
                } else {
                    console.log("another error happened:" + e.message);
                }
            }
        });
        return function () {
            unmounted = true;
            source.cancel("Cancelling in cleanup");
        };
    }, []);

    return {data, loading, error, errorMessage};
};

export default useAxiosFetch;

答案 2 :(得分:0)

完全可取消的例程示例,您根本不需要任何 CancelToken (Play with it here):

import React, { useState } from "react";
import { useAsyncEffect, E_REASON_UNMOUNTED } from "use-async-effect2";
import { CanceledError } from "c-promise2";
import cpAxios from "cp-axios"; // cancellable axios wrapper

export default function TestComponent(props) {
  const [text, setText] = useState("");

  const cancel = useAsyncEffect(
    function* () {
      console.log("mount");

      this.timeout(props.timeout);
   
      try {
        setText("fetching...");
        const response = yield cpAxios(props.url);
        setText(`Success: ${JSON.stringify(response.data)}`);
      } catch (err) {
        CanceledError.rethrow(err, E_REASON_UNMOUNTED); //passthrough
        setText(`Failed: ${err}`);
      }

      return () => {
        console.log("unmount");
      };
    },
    [props.url]
  );

  return (
    <div className="component">
      <div className="caption">useAsyncEffect demo:</div>
      <div>{text}</div>
      <button onClick={cancel}>Abort</button>
    </div>
  );
}

答案 3 :(得分:-1)

这就是我的方法,我认为它比这里的其他答案要简单得多:

import React, { Component } from "react";
import axios from "axios";

export class Example extends Component {
    _isMounted = false;

    componentDidMount() {
        this._isMounted = true;

        axios.get("/data").then((res) => {
            if (this._isMounted && res.status === 200) {
                // Do what you need to do
            }
        });
    }

    componentWillUnmount() {
        this._isMounted = false;
    }

    render() {
        return <div></div>;
    }
}

export default Example;