簡體   English   中英

如何解決 TypeError:使用 useMutation react hook 時無法讀取 react js 中未定義的屬性“then”

[英]How to solve TypeError: Cannot read property 'then' of undefined in react js when in use of useMutation react hook

我是 React 新手,我正在創建一個注冊頁面,用戶可以在其中注冊一個新帳戶。 一旦用戶插入他們的 email 的信息,全名,用戶名和密碼,一旦點擊注冊它就會通過 Axios POST 請求發送到服務器,用於通過 ZD3E28535C74CCEE29182AEB3CF837E98 發送用戶數據。 我按照反應查詢文檔中的示例進行操作,但出現 TypeError 錯誤:無法讀取第 57 行中未定義的屬性 'then'。請幫幫我。 先感謝您。 code [TypeError: 無法讀取未定義錯誤圖像的屬性 'then'

 const [data, setData] = useState({ email: "", fullname: "", username: "", password: "", }); const mutation = useMutation(newRegister => axios.post("/Account/Register",{newRegister}), { onSuccess: () => { setData('') }, }); function submit(e){ e.preventDefault(); mutation.mutate({ email:data.email, fullname:data.fullname, username:data.username, password:data.password}).then((res) => { res.data=setLoading(false); setMessage({ data: "Registered successfully.", type: "alert-success", }); setTimeout(() => { history.push("/login"); }, 3000); }).catch((err) =>{ alert(`Registered failed. ${err.message};`). return err;message. }) } function handleSubmit(e) { const newdata = {..;data }. newdata[e.target.id] = e.target;value; setData(newdata); }

useMutation function 返回類型不是Promise因此您將無法調用then (未知)方法。

由於您嘗試在突變成功后執行操作,因此您應該使用提供的onSuccess回調(您將忽略該回調):

const mutation = useMutation(
  newRegister => axios.post("/Account/Register", {newRegister}),
  { onSuccess: (data) => {        
      setData('');
      res.data = setLoading(false);
      setMessage({
        data: "Registered successfully.",
        type: "alert-success",
      });
      setTimeout(() => {
        history.push("/login");
      }, 3000);
    },
    onError(error) => {
      alert(`Registered  failed! ${error}.`);
    }
  });

function submit(e){
    e.preventDefault();
    mutation.mutate({
      email:data.email,
      fullname:data.fullname,
      username:data.username,
      password:data.password
    })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM