React Native:无法捕获引发的错误

时间:2020-10-10 16:17:40

标签: react-native

我正在尝试从signIn方法捕获错误,然后在代码中显示警报。我收到警告说“未处理的承诺被拒绝...”

export default function Login({navigation}){
    
    
    const [email, setEmail]  = React.useState('');
    const [password, setPassword] = React.useState('');
    const [showAlert, setShowAlert] = React.useState(false);
    const [showAlert2, setShowAlert2] = React.useState(false);
    const { signIn } = React.useContext(AuthContext);

    const submit = async() => {

        if (email === '' || password === '') {
            setShowAlert(true);
        } else {
            signIn(email, password).catch(error => 
                setShowAlert2(true)); // THIS NEVER GETS TRIGGERED, WHY?
        }
        
    }

    ...
}

signIn在我的App.js中定义如下:

const authContext = React.useMemo(() => {
    return {
      signIn: (email, password) => {
          auth().signInWithEmailAndPassword(email.email, password.password)
          .then((res) => {
            setIsLoading(false);
            setUser(res.user.uid);
          })
          .catch(error => {
            throw error; // This is the error that should be catched in "submit"
          })
      },
      signUp: () => {
        setIsLoading(false);
        setUser("test");
      },
      signOut: () => {
        setIsLoading(false);
        auth().signOut().then(() => console.log('User signed out!'));
        setUser(null);
      }
    };
}, []);

如您所见,我有时会执行“抛出错误”。那就是我想在上面的提交常量中捕获的错误。

这是我得到的错误:

TypeError: undefined is not an object (evaluating 'signIn(email, password).catch')

1 个答案:

答案 0 :(得分:3)

您需要返回该auth()调用,然后删除该catch,然后该错误将传递给任何调用signIn

    signIn: (email, password) => {
      return auth() // add return here
        .signInWithEmailAndPassword(email.email, password.password)
        .then(res => {
          setIsLoading(false);
          setUser(res.user.uid);
        })
    },

您甚至可以通过除去花括号并将其返回来进一步清理。箭头将自动返回下一个值:

  signIn: (email, password) =>
    auth()
      .signInWithEmailAndPassword(email.email, password.password)
      .then(res => {
        setIsLoading(false);
        setUser(res.user.uid);
      });

您所看到的错误基本上是在返回的catch值上找不到signIn方法。这是正确的,因为在您的版本signIn中不返回任何内容。 signIn函数必须返回一个承诺(它只是一个具有thencatch之类的方法的对象);如果您返回承诺,则它会具有该catch方法,然后可以调用该方法。