React Native 错误 must be used from main thread only

React Native 2020-03-26 阅读 212 评论 0

问题描述

使用 Objective C 自定义模块,在 iOS 下创建一个 RCT_EXPORT_METHOD 方法如下:

RCT_EXPORT_METHOD(startPay:(NSString*)tn :(NSString*)mode)
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIViewController *rootViewController = window.rootViewController;
    [[UPPaymentControl defaultControl] startPay:tn
                                     fromScheme:@"UPPayDemo" mode:mode
                                 viewController:rootViewController];
}

React Native 的 js 调用后,Xcode 出现一个错误,显示需要在主线程使用。

-[UIApplication keyWindow] must be used from main thread only
-[UIWindow rootViewController] must be used from main thread only

[UIApplication keyWindow] must be used from main thread only,[UIWindow rootViewController] must be used from main thread only

解决方法

改用在主线程调用,使用 dispatch_async(dispatch_get_main_queue(), ^{}),将代码移到块里面。

RCT_EXPORT_METHOD(startPay:(NSString*)tn :(NSString*)mode)
{
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        UIViewController *rootViewController = window.rootViewController;
        [[UPPaymentControl defaultControl] startPay:tn
                                         fromScheme:@"UPPayDemo" mode:mode
                                     viewController:rootViewController];
    });
}
最后更新 2020-03-26