In one word would be: PRACTICE. In a sentence would be: Repetition is the mother of skill.
Indeed, grammatical mistakes can be avoided only if you learn the grammatical rules: tenses, aspects, modals, sequence of tenses, conditionals, etc. The more you practise, the less mistakes you will make. Unfortunately, we all make mistakes ( after all we are human beings, or not?). You have to study all the grammar rules and then practice it. And if you have problems with these rules, feel free and ask in this forum. I'm sure that somebody will always answer to your questions.
Have nice day ( life )