React Native(Expo) login函数报TypeError错误原因排查求助
错误原因分析
你的代码存在Promise链式调用的语法错误,具体问题如下:
括号不匹配导致链式结构混乱
你在.then的回调函数中,navigation.reset(...)之后直接写了.catch,但这个.catch被错误绑定到了navigation.reset()的返回值上。而navigation.reset()并不是Promise对象,没有.catch方法,因此会抛出undefined is not an object (evaluating 'navigation.reset(...).catch')的错误。看你的代码结构:
async function login(){ await signInWithEmailAndPassword (auth, email, input) .then(value=>{ console.log('login ok') navigation.reset({ index: 0, routes: [{name:'Home'}] }) .catch(error => console.log(error)); // 此处.catch位置错误,且.then的回调大括号未闭合 }) };你没有闭合
.then回调的大括号,导致.catch被解析成navigation.reset()的方法调用,而非signInWithEmailAndPassword的Promise链式调用的一部分。async/await与.then混用的冗余问题
既然使用了async/await,就没必要嵌套.then/.catch,两种写法混合容易导致结构混乱,增加出错概率。
修正后的代码示例
可以选择以下两种规范写法之一:
写法一:仅使用async/await + try/catch
async function login(){ try { await signInWithEmailAndPassword(auth, email, input); console.log('login ok'); navigation.reset({ index: 0, routes: [{name:'Home'}] }); } catch (error) { console.log(error); } };
写法二:仅使用Promise链式调用(不使用async/await)
function login(){ signInWithEmailAndPassword(auth, email, input) .then(value=>{ console.log('login ok'); navigation.reset({ index: 0, routes: [{name:'Home'}] }); }) .catch(error => console.log(error)); };
内容的提问来源于stack exchange,提问作者Wagner Amarelo
相关产品推荐
相关产品推荐

