【问题标题】:Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'clientToken')未处理的拒绝(TypeError):无法读取未定义的属性(读取“clientToken”)
【发布时间】:2021-09-30 14:49:49
【问题描述】:

虽然clientToken 已定义并赋值,但它显示未定义的属性,为什么?

API 调用工作正常,URL 正常,但仍然显示此错误,谁能帮我解决这个问题。

以下是错误详情。

 if (info && info.error) {
  26 |     setInfo({ ...info, error: info.error });
  27 |   } else {
> 28 |     const clientToken = info.clientToken;
     | ^  29 |     setInfo({ clientToken });
  30 |   }
  31 | });

getToken 对象在下面。

  const getToken = (userId, token) => {
    getmeToken(userId, token).then(info => {
      // console.log("INFORMATION", info);
      if (info && info.error) {
        setInfo({ ...info, error: info.error });
      } else {
        const clientToken = info.clientToken;
        setInfo({ clientToken });
      }
    });
  };

getmeToken 组件如下。

export const getmeToken = (userId, token) => {
    return fetch(` ${API}/payment/gettoken/${userId}`, {
        method: "GET",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`
        }
    }).then(response => {
        return response.json();
    })
    .catch(err => console.log(err))
}

谁能帮我解决这个问题?

【问题讨论】:

  • info 没有属性clientToken,因为它返回undefined。登录info并检查其结构
  • const Paymentb = ({ products, setReload = f => f, reload = undefined }) => { const [info, setInfo] = useState({ loading: false, success: false, clientToken:空,错误:“”,实例:{} });
  • 函数getmeToken返回response.json();这是你的info而不是状态[info, setInfo]
  • getmeToken(userId, token).then(info => { 在这个块中 info 不是一个状态
  • @VitaliyRayets 是的

标签: javascript node.js reactjs mern


【解决方案1】:

在您的else 条件下,您永远不会检查info 是否已定义并且很可能没有。问题可能不是来自clientToken 本身,而是来自infoundefinednull

你可以尝试做这样的事情:

if (info) {
  if (info.error) {
    setInfo({ ...info, error: info.error });
  } else {
    const clientToken = info.clientToken;
    setInfo({ clientToken });
  }
}

【讨论】:

  • const Paymentb = ({ products, setReload = f => f, reload = undefined }) => { const [info, setInfo] = useState({ loading: false, success: false, clientToken:空,错误:“”,实例:{} });
  • 好的,然后将变量info从你的回调中重命名为infoResultgetmeToken(userId, token).then(infoResult => ... ),它可能与你的状态info变量发生冲突。
  • 没有影响
猜你喜欢
  • 2021-11-15
  • 2022-11-26
  • 1970-01-01
  • 2019-04-07
  • 2021-11-19
  • 1970-01-01
  • 2022-06-19
  • 2019-07-19
  • 2019-06-03
相关资源
最近更新 更多