MAUI应用程序在发布模式下无法工作,但在调试模式下完美运行。

10

我的 MAUI 应用在模拟器中以调试模式运行良好,但在发布模式下运行时无法工作(在模拟器或实体设备上均不起作用),会崩溃。

我正在使用名为 CommunityToolkit.Mvvm 的库,并使用 Mvvm 架构。我提到这一点是因为我不知道是否导致了问题。

我在我的实体设备上下载了一个名为 Crash Log Viewer 的应用程序,以检查应用程序出现的崩溃和错误,我得到了以下错误:

This information is generated from the Crash Log View application. - https://play.google.com/store/apps/details?id=com.arumcomm.crashlogviewer

Process: com.companyname.ventas_citel
PID: 12230
UID: 10313
Flags: 0x20c8be44
Package: com.companyname.ventas_citel v1 (1.0)
Foreground: No
Process-Runtime: 63820382
Build: samsung/a10sub/a10s:11/RP1A.200720.012/A107MUBU6CVG3:user/release-keys

android.runtime.JavaProxyThrowable: System.FieldAccessException: Field `Microsoft.Maui.Controls.VisualElement:ZIndexProperty' is inaccessible from method `Ventas_Citel.Views.Login.Login:InitializeComponent ()'

   at Ventas_Citel.Views.Login.Login..ctor(LoginViewModel viewModel)
   at System.Reflection.RuntimeConstructorInfo.InternalInvoke(Object , Object[] , Boolean )
   at System.Reflection.RuntimeConstructorInfo.DoInvoke(Object , BindingFlags , Binder , Object[] , CultureInfo )
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags , Binder , Object[] , CultureInfo )
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite , RuntimeResolverContext )
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2[[Microsoft.Extensions.DependencyInjection.ServiceLookup.RuntimeResolverContext, Microsoft.Extensions.DependencyInjection, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[System.Object, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].VisitCallSiteMain(ServiceCallSite , RuntimeResolverContext )
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite , RuntimeResolverContext , ServiceProviderEngineScope , RuntimeResolverLock )
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite , RuntimeResolverContext )
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2[[Microsoft.Extensions.DependencyInjection.ServiceLookup.RuntimeResolverContext, Microsoft.Extensions.DependencyInjection, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[System.Object, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].VisitCallSite(ServiceCallSite , RuntimeResolverContext )
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c_DisplayClass2_0.<RealizeService>b_0(ServiceProviderEngineScope )
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type , ServiceProviderEngineScope )
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type )
   at Microsoft.Maui.MauiContext.WrappedServiceProvider.GetService(Type serviceType)
   at Microsoft.Maui.Controls.ShellContent.<>c_DisplayClass19_0.<Microsoft.Maui.Controls.IShellContentController.GetOrCreateContent>b_0()
   at Microsoft.Maui.Controls.ElementTemplate.CreateContent()
   at Microsoft.Maui.Controls.Internals.DataTemplateExtensions.CreateContent(DataTemplate self, Object item, BindableObject container)
   at Microsoft.Maui.Controls.ShellContent.Microsoft.Maui.Controls.IShellContentController.GetOrCreateContent()
   at Microsoft.Maui.Controls.Platform.Compatibility.ShellSectionRenderer.OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
   at AndroidX.Fragment.App.Fragment.n_OnCreateView_Landroid_view_LayoutInflater_Landroid_view_ViewGroup_Landroid_os_Bundle_(IntPtr , IntPtr , IntPtr , IntPtr , IntPtr )
   at Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PPLLL_L(_JniMarshal_PPLLL_L , IntPtr , IntPtr , IntPtr , IntPtr , IntPtr )
    at crc640ec207abc449b2ca.ShellSectionRenderer.n_onCreateView(Native Method)
    at crc640ec207abc449b2ca.ShellSectionRenderer.onCreateView(ShellSectionRenderer.java:42)
    at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2995)
    at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:523)
    at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
    at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1840)
    at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1764)
    at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1701)
    at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2849)
    at androidx.fragment.app.FragmentManager.dispatchViewCreated(FragmentManager.java:2777)
    at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3020)
    at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:551)
    at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
    at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1840)
    at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1764)
    at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1701)
    at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2849)
    at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2784)
    at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:262)
    at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:478)
    at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:246)
    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1435)
    at android.app.Activity.performStart(Activity.java:8231)
    at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3872)
    at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
    at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
    at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2336)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:246)
    at android.app.ActivityThread.main(ActivityThread.java:8653)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)

似乎错误出现在 LoginViewModel 中,因此我共享了我的代码文件: MauiProgram
    public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder.UseMauiApp<App>().UseMauiCommunityToolkit();

        builder
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            });


        //views
        builder.Services.AddSingleton<Login>();
        builder.Services.AddSingleton<Inventario>();
        builder.Services.AddSingleton<Clientes>();
        builder.Services.AddSingleton<Ventas>();
        builder.Services.AddSingleton<CuentasPorCobrar>();


        //viewModels
        builder.Services.AddSingleton<LoginViewModel>();
        builder.Services.AddSingleton<InventarioViewModel>();
        builder.Services.AddSingleton<ClientesViewModel>();
        builder.Services.AddSingleton<VentasViewModel>();
        builder.Services.AddSingleton<CuentasPorCobrarViewModel>();


        // services
        builder.Services.AddHttpClient<ILoginService, LoginService>();


        return builder.Build();


    }
}

LoginViewModel

public partial class LoginViewModel : BaseViewModel
{
    [ObservableProperty]
    string uuid;

    [ObservableProperty]
    private string _email;

    [ObservableProperty]
    private string _password;

    [ObservableProperty]
    private bool _isEnabled = true;

    private readonly ILoginService _loginService;
    public LoginViewModel(ILoginService loginService)
    {
        ComprobarUUID();
        _loginService = loginService;
        IsEnabled = true;
    }

    private async void ComprobarUUID()
    {
        // .. code
    }

    private async void CargarUUIDPorPrimeraVez()
    {
        // .. code
    }

    [RelayCommand]
    async void Copiar()
    {
        // .. code
    }



}

基础视图模型

 public partial class BaseViewModel : ObservableObject
    {
        [ObservableProperty]
        private bool _isBusy;

        [ObservableProperty]
        private string _title;
    }

Login.xaml.cs

public partial class Login : ContentPage
{
    public Login(LoginViewModel viewModel)
    {
        InitializeComponent();
        BindingContext = viewModel;
    }
}

我一直在努力开发这个应用程序,而且一直都是通过调试模式构建这个应用程序,但今天我必须将这个应用程序交给团队使用,但它却不能正常工作。

我该如何解决这个错误?您需要更多的代码吗?


异常发生在“Login”页面构造函数运行“InitializeComponent”的过程中。这意味着XAML中的某些内容引起了问题。考虑到它在调试模式下工作正常,听起来像是Maui的一个错误。如果Alexandar的建议没有解决问题,请尝试注释掉login.xaml中的内容,以隔离导致问题的行。如果您找出了导致问题的行,请将xaml减少到最小值,然后将完整的xaml添加到问题中。如果没有人能够解决问题,则在“github maui issues”上创建一个新问题。 - ToolmakerSteve
@Reyneer,这里有一个类似的问题和答案:https://dev59.com/pnwQtIcB2Jgan1znS8HB#74556855 - SaddamBinSyed
如果您在 iOS 物理设备上遇到问题,可能与此相关:https://github.com/dotnet/maui/issues/12316 - Caio
7个回答

11

从xaml中移除zIndex,并使用其他方法。

我花了很长时间才找到在发布模式下导致崩溃的原因,而这就是解决方法。简直不敢相信Maui已经投入生产了。


1
这正是我所做的,而且还起作用了!我甚至无法相信 MAUI 会有这种类型的错误。难以置信! - Reyneer Leon

6

您可以尝试禁用编译绑定,方法如下:

[XamlCompilation (XamlCompilationOptions.Skip)]
public partial class Login : ContentPage
{
    public Login(LoginViewModel viewModel)
    {
        InitializeComponent();
        BindingContext = viewModel;
    }
}

2
这解决了我的问题..但是..为什么呢?这是maui中已知的问题吗? - NPadrutt

4
在我的情况下,我只在Android平台上遇到了问题。相同的调试版本可以完美运行,但发布版本在启动时崩溃了。 对我来说,解决方案是在项目属性中取消勾选AOT编译,这在调试时默认未勾选,但在发布时勾选了。

enter image description here


同样的问题。谢谢。还没有找到为什么这是个问题的原因。 - undefined

2

我遇到了同样的问题。 在我的情况下是Xaml错误。 以下代码存在错误。

<StackLayout Orientation="Horizontal"
            RadioButtonGroup.GroupName="interest" 
            RadioButtonGroup.SelectedValue="{Binding rdinterestTaxRATIO}">
<RadioButton Content="15.4%" 
             Value="15.4"
             RadioButtonGroup.GroupName="interest" 
             Margin="15"
             IsChecked="True"/>
<RadioButton Content="1.4%" 
             Value="1.4"
             RadioButtonGroup.GroupName="interest" 
             Margin="15"
             IsChecked="False"/>
<RadioButton Content="0%" 
             Value="0"
             RadioButtonGroup.GroupName="interest" 
             Margin="15"
             IsChecked="False"/>

以下代码一切正常。
<StackLayout Orientation="Horizontal"
            RadioButtonGroup.GroupName="interest" 
            RadioButtonGroup.SelectedValue="{Binding rdinterestTaxRATIO}">
<RadioButton Content="15.4%" 
                Value="15.4"
                Margin="15"
                IsChecked="True"/>
<RadioButton Content="1.4%" 
                Value="1.4"
                Margin="15"
                IsChecked="False"/>
<RadioButton Content="0%" 
                Value="0"
                Margin="15"
                IsChecked="False"/>

2
在MainPage.xaml.cs文件的类语句上方添加"[XamlCompilation(XamlCompilationOptions.Skip)]",并在项目属性中禁用AOT开关对我也非常有效。
我的MainPage文件的第一部分:
命名空间your_namespace

{

[XamlCompilation(XamlCompilationOptions.Skip)]

public partial class MainPage : ContentPage

{

1
这些答案最终对我很有帮助,对我来说,这也是一个仅限于Android的问题,一个XAML代码错误。当设置了错误的StaticResource作为TextColor时,它会在页面上崩溃。
我原本使用的是:
TextColor="{StaticResource PrimaryColor}",但应该是TextColor="{StaticResource Primary}"

奇怪的是,在调试器中这个问题没有出现,但在部署到我的手机上后显示的颜色却是错误的。只要在调试过程中,它就能正常工作,但一旦我断开手机连接,它就会崩溃。我还尝试了在未连接的情况下使用该应用程序。显然,发布版本也无法正常工作。
希望这对其他人有所帮助。

0
在这里我想提出我的两分钱,我在我的XAML中又遇到了一个问题 - 最近更改了视图模型类型名称,但没有更新页面的以匹配。
1. 根据建议添加了,验证它跳过了编译错误。 2. 更正了以匹配更新的视图模型。 3. 移除了,验证应用程序按预期工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接