警告:UIViewRepresentable 中的 "Modifying state during view update, this will cause undefined behavior."

Warning: "Modifying state during view update, this will cause undefined behavior." in UIViewRepresentable

所以我有一个 UIViewRepresentable,它包装了一个 UITextField,我在 textFieldshouldChangeCharactersInRange 方法中遇到了这个错误:

struct MyTextField: UIViewRepresentable {

    class Coordinator: NSObject, UITextFieldDelegate, ObservableObject {
    
        @Binding var text: String

        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            if let currentValue = textField.text as NSString? {
                let proposedValue = currentValue.replacingCharacters(in: range, with: string)
                text = proposedValue // Warning is thrown from here
            }
            return true
        }
    }
...

在此处更新绑定而不触发此警告的正确方法是什么?

在下一个偶数循环时更新,例如

DispatchQueue.main.async {
    text = proposedValue
}