'ServerScriptService.leaderstats:41: attempt to index nil with 'leaderstats' in roblox

This is my code

game:BindToClose(function(player)
    for _, Player in pairs(game.Players:GetPlayers()) do
        
        local playerUserId = "player_"..Player.UserId

        local clicksValue = player.leaderstats.Clicks.Value

        local success, errormessage = pcall(function()
            clicksDataStore:SetAsync(playerUserId, clicksValue)
         
        end)
    end
end)

Please help me becouse I disconnect the game, console get me this error:



Solution 1:[1]

Check if player.leaderstats or clicksValue is not nil before calling:

local success, errormessage = pcall(function()
    clicksDataStore:SetAsync(playerUserId, clicksValue)

Solution 2:[2]

DataModel:BindToClose doesn't pass any arguments to the callback. I suggest you remove the player parameter in the callback and change the player in player.leaderstats.Clicks.Value to Player

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gaspar
Solution 2 Keilorus