使用异步和等待从不正确的线程访问的领域

Realm accessed from incorrect thread using async and await

运行 下面的代码我得到“从不正确的线程访问的领域”。第二 try! realm.write({ 行出错,第一行写入没有错误。知道如何解决吗?

let realm = try! await Realm()
                        print("User Realm User file location: \(realm.configuration.fileURL!.path)")
                        try! realm.write { // <= No error here
                            realm.add(groups, update: .modified)
                        }
                        StartApp._Groups = groups
                        if let items  = await api.getArticles(aricleIDs: ids) {
                            try! realm.write({ // <= Error here
                                realm.add(items, update: .modified)
                            })
                            StartApp._Items = items
                            var index = 0
                            StartApp._Items = StartApp.Items.map { item in
                                item.i = index
                                index = index + 1
                                return item
                            }
                            groups.forEach { group in
                                group.items = items.filter({ [=10=].groupId == group.id })
                            }
                        }

我修复了以下内容,删除了 await Realm() 并将写入合并到一个

DispatchQueue.main.async{
                        do {
                            let realm = try Realm()
           
                            var index = 0
                            items.forEach { item in
                                item.i = index
                                index = index + 1
                            }
                            try realm.write({
                                realm.add(groups, update: .modified)
                                realm.add(items, update: .modified)
                               }
                            })
                        } catch {
                            print("Realm error: \(error)")
                        }
                    }