The background of this event is recorded in Numbers 25. In it, some of the Israelites were committing fornication with the women of Moab. Consequently, God was provoked to anger and He cast a plague over Israel. Then, Phinehas took a spear and drove it through a couple in the act of fornication. He obtained mercy from God, terminated the plague, and was regarded as being a righteous man due to his desire for righteousness. His deed would be blessed and remembered in every future generation. The reality of his faith was demonstrated before other men. This is a testimonial of faithfulness, not justification before God. Notice how other Bible translations render this verse:
"Because of this, Phinehas was considered righteous forever, throughout every generation." (Psalm 106:31, God's Word Translation)
"This was counted for him as a righteous deed for all generations to come." (Psalm 106:31, New American Bible Revised Edition)
"for this he is the example of uprightness, from age to age for ever." (Psalm 106:31, New Jerusalem Bible)
Following is an excerpt from the New English Translation on Psalm 106:31:
Following is an excerpt from the Jamieson-Fausset-Brown Bible Commentary on Psalm 106:31:
"31. counted … righteousness—"a just and rewardable action." for—or, "unto," to the procuring of righteousness, as in Ro 4:2; 10:4. Here it was a particular act, not faith, nor its object Christ; and what was procured was not justifying righteousness, or what was to be rewarded with eternal life; for no one act of man's can be taken for complete obedience. But it was that which God approved and rewarded with a perpetual priesthood to him and his descendants (Nu 25:13; 1 Ch 6:4, etc.)."
God certainly rewards Christians for their faithfulness to Him. He blessed those who love Him and serve Him. But we are not justified by works of righteousness (Titus 3:5). We are saved because God is merciful. He saved us in spite of our unrighteousness (Deuteronomy 9:3-6; Ephesians 2:4-9). The gospel requires that one must believe in order to receive justification (John 20:31; Acts 16:29-32; Romans 3:28; Galatians 3:4-9; 2 Timothy 3:15; Revelation 21:6; 22:17). This righteous act of Phineas has nothing to do with him meriting justification in part by good works. God simply deemed this man's conduct to be righteous, and assured that the priesthood would not depart from his line.