zoukankan      html  css  js  c++  java
  • react报错:Can‘t perform a React state update on an unmounted component

     

     解决方案:

    //生成cancelToken,用于取消请求
    const getCancelSource = () => {
      return axios.CancelToken.source()
    }  
    
    
    
      //挂载时异步获取所属分类数据
      useEffect(() => {
        const source = getCancelSource()
        Api.light.category(source.token).then((res) => {
          if (res.state === 1) {
            const category = formatCategory({ categoryOptions: res.data })
            setCategoryOptions(category)
            console.log('category')
          }
        }).catch(err => {
          console.log(err)
        })
        return () => {
          console.log('卸载')
          source.cancel()
        }
      }, [])

    参考链接:http://www.axios-js.com/zh-cn/docs/#%E5%8F%96%E6%B6%88

    const CancelToken = axios.CancelToken;
    const source = CancelToken.source();
    
    axios.get('/user/12345', {
      cancelToken: source.token
    }).catch(function(thrown) {
      if (axios.isCancel(thrown)) {
        console.log('Request canceled', thrown.message);
      } else {
         // 处理错误
      }
    });
    
    axios.post('/user/12345', {
      name: 'new name'
    }, {
      cancelToken: source.token
    })
    
    // 取消请求(message 参数是可选的)
    source.cancel('Operation canceled by the user.');

     axios config的一个字段:

      // `cancelToken` 指定用于取消请求的 cancel token
      // (查看后面的 Cancellation 这节了解更多)
      cancelToken: new CancelToken(function (cancel) {
      })

  • 相关阅读:
    树剖学习笔记
    网络命令
    shell编程
    Shell 脚本常用命令
    WP7系统托盘和应用程序栏
    Ajax的同步与异步
    WP7推送通知服务
    (转)Silverlight控件关系理解
    (转) silverlight 样式学习
    (转C#中Enum用法小结)
  • 原文地址:https://www.cnblogs.com/xutongbao/p/15264328.html
Copyright © 2011-2022 走看看