首页 > 解决方案 > TypeError:无法设置未定义的属性“数据”

问题描述

我目前正在做一个注册页面,使用 react.js 并使用 useMutation 使用 Axios 调用 API。用户可以注册,但显示错误信息[注册失败!TypeError: Cannot set property 'data' of undefined ] 但注册后应该提示成功消息。如何解决这个错误。

const { Axios } = useContext(ApiContext);
const adduser = ({data}) => {
    Axios
    .post("/Account/Register", {
      email: data.email,
      fullname: data.fullname,
      username: data.username,
      password: data.password,
    });
}


  const [visible,setVisible] = useState();
  const [loading, setLoading] = useState(false)
  const [message, setMessage] = useState();
  const history = useHistory();
  const [data, setData] = useState({
    email: "",
    fullname: "",
    username: "",
    password: "",
  });
  const {mutate} = useMutation((adduser),
    { 
    onSuccess: (res) => {        
      setData({
        email: data.email,
        fullname: data.fullname,
        username: data.username,
        password: data.password,
      });
      setMessage({
        data: "Registered successfully.",
        type: "alert-success",
      });
      setTimeout(() => { 
        res.data = setLoading(true);
        history.push("/login");
      }, 3000);
    },
    onError: (error) => {
      alert(`Registered  failed! ${error}.`);
    }
  });

  const onAddUser = async e => {
    e.preventDefault()
    await mutate({ data})
}
const handleSubmit = async e =>  {
    const newdata = { ...data };
    newdata[e.target.id] = e.target.value;
    setData(newdata);
  }

这些是代码。

这是显示的错误 在此处输入图像描述

谢谢 ...

标签: javascriptreactjsreact-hooks

解决方案


推荐阅读