首页 > 解决方案 > 数据从节点返回时 MERN 堆栈出现问题

问题描述

我正在使用 Fetch API 将数据发布到我的节点服务器。我看到了一些我无法理解的行为,需要一些帮助来解决。当用户单击一个按钮时,会打开一个带有几个字段的表单。在点击提交时,数据被传递到节点服务器。首先,它为 Mongo 创建一条新记录并将数据保存在集合中。保存后,我想从其他几个集合中获取一些数据,然后将信息发送回我的反应应用程序。

这就是我所看到的。

  1. 如果我只保存数据而不做获取部分并发回这样的消息

    res.status(201).json({"message":"data received"}) 然后在我的控制台中关闭模式后,我看到消息“已接收数据”。

  2. 但是,如果我执行 fetch 部分,这基本上意味着多几毫秒的延迟,那么一旦模式关闭,此消息就会在反应控制台中闪烁。

    警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要解决此问题,请在 useEffect 清理函数中取消所有订阅和异步任务。DOMException:用户中止了请求。

这是我在反应中的提交处理程序

const submitHandler = async(event) => {
        event.preventDefault()
        try {
            const responseData = await sendRequest('http://localhost:5000/challenge/createChallenge', 'POST',
                JSON.stringify({
                    location: selectedOption,
                    format: selectedOption1,
                    date: selectedDate.toString(),
                    opponent: props.initialValues,
                    month: cMonth,
                    year: cYear,
                    player: auth.profile.MemberName
                }),
              {
                'Content-Type': 'application/json',
                Authorization: 'Bearer ' + auth.token
              })    
              console.log(responseData)
        } catch (err){
            console.log(err)
        }
    }

这是我的 http-hook,这是我正在使用的自定义钩子

import { useState, useCallback, useRef, useEffect } from 'react'

export const useHttpClient = () => {
    const [isLoading, setIsLoading] = useState(false)
    const [error, setError] = useState(false)

    const activeHttpRequests = useRef([])

    const sendRequest = useCallback(async (url, method = 'GET', body = null, headers = {}) => {

        setIsLoading(true)
        const httpAbortCtrl = new AbortController()
        activeHttpRequests.current.push(httpAbortCtrl)
       try {
        const response =  await fetch(url, {
            method,
            body,
            headers,
            signal: httpAbortCtrl.signal
        })

        const responseData = await response.json()
        activeHttpRequests.current = activeHttpRequests.current.filter(reqCtrl => reqCtrl !== httpAbortCtrl)
        if(!response.ok){
            throw new Error(responseData.message)
        }
        setIsLoading(false)
        return responseData

       } catch (err){
           setError(err.message)
           setIsLoading(false)
           throw err
       }
    }, [])

    const clearError = () => {
        setError(null)
    }

    useEffect(() => {
        return () => {
            activeHttpRequests.current.forEach(abortCtrl => abortCtrl.abort())
        }
    }, [])

    return { isLoading, error, sendRequest, clearError}
}

有人可以帮忙吗?我不确定如何解决这个问题。我检查了这个错误的原因,而互联网上的一些内容给了我一些线索。但我还不够清楚,无法解决这个问题。

标签: reactjs

解决方案


推荐阅读