简体   繁体   English

React Native Unhandled promise 拒绝 | React-Native, 异步,

[英]React Native Unhandled promise rejection | React-Native, Async,

I keep getting an Unhandled Promise Rejection我一直收到未处理的 Promise 拒绝
I'm Running React-Native with the EXPO CLI and am using React Hook Forms我正在使用 EXPO CLI 运行 React-Native 并使用 React Hook Forms

Things I've tried and nothing has changed:我尝试过的事情没有任何改变:

  1. Gave my api (NodeJS) an SSL (I know ios wants one)给我的 api (NodeJS) 一个 SSL (我知道 ios 想要一个)
  2. Refactored to regular and react hooks for each field重构为每个字段的常规和反应挂钩
  3. Changed the BaseUrl to 10.0.2.2 AND THEN TRIED my personal IP address.将 BaseUrl 更改为 10.0.2.2,然后尝试使用我的个人地址 IP。
  4. Changed to normal Promise AND THEN TRIED Axios calls更改为正常 Promise 然后尝试拨打 Axios

The console log just inside the onSubmit function returns the data from the form, but it stops there. onSubmit function 内的控制台日志返回表单中的数据,但它停在那里。

The Full Error:完整错误:

[Unhandled promise rejection: TypeError: (0, _auth.loginUser) is not a function. (In '(0, _auth.loginUser)(data)', '(0, _auth.loginUser)' is undefined)] at node_modules/react-hook-form/dist/index.cjs.development.js:1204:67 in at [native code]:null in flushedQueue at [native code]:null in callFunctionReturnFlushedQueue [未处理的 promise 拒绝:TypeError:(0,_auth.loginUser)不是 function。(在“(0,_auth.loginUser)(数据)”中,“(0,_auth.loginUser)”未定义)] at node_modules/ react-hook-form/dist/index.cjs.development.js:1204:67 在 [native code]:null 在 flushedQueue 在 [native code]:null 在 callFunctionReturnFlushedQueue

Login Component Code:登录组件代码:

import React from 'react';
import { StyleSheet, View, Text } from 'react-native';

import Input from '../Input';
import Button from '../Button';
import Link from '../Link';
import { useForm, Controller } from "react-hook-form";
import { loginUser } from '../../helpers/data/auth';

const EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

export default function Login() {
  const { control, handleSubmit, errors } = useForm();

  const onSubmit = async (data) => {
    console.log(data)
    let response = await loginUser(data)
    if (response.status >= 200 && response.status < 300) {
      console.log(response)
    } else {
      error
    }
  }

  return (
    <View style={styles.container}>

      <Controller
        control={control}
        name="email"
        defaultValue=''
        rules={{
          required: {value: true, message: 'Email is required' },
          pattern: {
            value: EMAIL_REGEX,
            message: 'Not a valid email'
          }
        }}
        render={({ onChange, onBlur, value }) => (
        <Input
          error={errors.email}
          errorText={errors?.email?.message}
          onBlur={onBlur}
          onChangeText={value => onChange(value)}
          value={value}
          placeholder={'Email'}
          textAlign={'center'}
        />
        )}
      />

      <Controller
        control={control}
        name="password"
        defaultValue=''
        rules={{ required: {value: true, message: 'Password is required' } }}
        render={({ onChange, onBlur, value }) => (
          <Input
            error={errors.password}
            errorText={errors?.password?.message}
            onBlur={onBlur}
            onChangeText={value => onChange(value)}
            value={value}
            secureTextEntry={true}
            placeholder={'Password'}
            textAlign={'center'}
          />
        )}
      />
      <Button onPress={handleSubmit(onSubmit)} label="LOGIN"/>

      <View style={styles.row}>
        <Text style={styles.text}>Forgot your login details? </Text>
        <Link onPress={() => {}} label='Get help signing in.'/>
      </View>

    </View>
  )
}

loginUser Fetch Call:登录用户获取调用:

import { baseUrl } from '../apiKeys.json';

const loginUser = async (data) => {
  const response = await fetch(`${baseUrl}/auth/signin`, {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  });
  return response.json();
}

export default { loginUser };

Save me...救我...

Add the export infront of constconst前面添加export

import { baseUrl } from '../apiKeys.json'; //not quite remember whether u can do this.

//add the export here.

export const loginUser = async (data) => {
  const response = await fetch(`${baseUrl}/auth/signin`, {
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  });
  return response.json();
}

Unhandled promise rejection means that your code doesn't handle if there's an error occurring. Unhandled promise rejection意味着如果发生错误,您的代码将无法处理。 In your function , use trycatch statement.在您的function中,使用trycatch语句。 Any error occurring will be handled by catch发生的任何错误都将由catch处理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM