首页 > 解决方案 > 如何在内部加载的按钮单击中修复“警告:无法对未安装的组件执行 React 状态更新”?

问题描述

我基本上有这个按钮来分派一个请求,当请求完成时我将 load 设置为 false,我遇到了这个常见的问题,即当组件被卸载时,react 无法处理状态。我尝试使用 useRef hooks 设置 _isMounted 状态,就像在这个类似的问题Cleanup memory leaks on an Unmounted Component in React Hooks 但它没有用。

这是按下按钮时的功能

const handleSubmit = useCallback(
        async e => {
          e.preventDefault()
    
          try {
            setLoading(true)
    
            if (!email || !password) {
              alert('warning', {
                message: 'Ops...',
                description: 'Preencha email e senha para continuar.',
              })
    
              return
            }
    
            const data = {
              email,
              password,
            }
    
            const { setToken } = SessionActions
            const { setCustomer } = CustomerActions
    
            const request = await api.post('/sessions', data)
    
            const { token } = request.headers
            const { customer } = request.data
    
            alert('success', {
              message: 'Seja bem-vindo ao GCM VIP!',
            })
    
            dispatch(setCustomer(customer))
            dispatch(setToken(token))
          } catch (err) {
            alert('error', {
              message: 'Ops...',
              description:
                'Ocorreu algum problema, entre em contato com o suporte.',
            })
          } finally {
            setLoading(false)
          }
        },
        [email, password, dispatch],
      )

这是按钮本身

<Button
            data-testid="submit"
            id="submit"
            type="primary"
            size="large"
            htmlType="submit"
            loading={loading}
          >
            Enter
          </Button>

标签: reactjs

解决方案


推荐阅读